
USE [DBAObjects]
GO

-- The following code is basically tied to rights issues that I decided to look 
-- into after reading this article: 
-- http://www.sqlservercentral.com/articles/Administration/64974/
-- While it doesn't so much cover rights it got me thinking.  The code here is 
-- directly to resolve permissions issues that could cause logons to be denied
-- because the user doesn't have sufficient rights to log their logon.  This was
-- tested with a user that had ONLY a sql logon to the server and no other 
-- rights.  That user was unable to logon.  I have added a login called
-- AuditCredLogin and a user AuditCredUser, this user exists in both the Audit
-- and Repository databases.  This login has a long nasty password assembled 
-- from 2 GUIDs that are generated locally, the password is not displayed and 
-- does not need to be know, it is NEVER used to actually login to the server, 
-- therefore is disabled.

DECLARE @pwd VARCHAR(80)

-- Generate random LONG password, we don't need to know what it is..
SELECT @pwd = CONVERT( VARCHAR(38), NEWID() ) + ' - ' + CONVERT( VARCHAR(38), NEWID() )

IF NOT EXISTS ( SELECT 'X' FROM master.sys.server_principals WHERE name = 'AuditCredLogin' )
BEGIN -- Login doesn't already exist so we need to create it.
     DECLARE @cmd varchar(8000)

     SELECT @cmd = 'CREATE LOGIN [AuditCredLogin] WITH PASSWORD = '''
                 + @pwd
                 + ''', '
                 + 'DEFAULT_DATABASE = [tempdb], CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF '
     EXEC ( @cmd )
END
GO

-- Permission needed for Logon Trigger.
DECLARE @cmd varchar(8000)

SELECT @cmd = 'USE [master]; GRANT VIEW SERVER STATE TO [AuditCredLogin];'
EXEC ( @cmd )
GO

-- Disable Logon
DECLARE @cmd varchar(8000)

SELECT @cmd = 'ALTER LOGIN [AuditCredLogin] DISABLE;'
EXEC ( @cmd )
GO

IF NOT EXISTS ( SELECT 'X' FROM sys.database_principals WHERE name = 'AuditCredUser' )
BEGIN -- User doesn't already exist so we need to create it.
     DECLARE @cmd varchar(8000)

     SELECT @cmd = 'CREATE USER [AuditCredUser] FROM LOGIN [AuditCredLogin]; '
     EXEC ( @cmd )
END
GO

-- One additional point here, if this database is to be available for logging by
-- all other databases this next line should be executed, it is currently not
-- included for security reasons.  However enabling guest access to the database
-- does NOT grant grant guest access to the server and the login must already
-- have been authenticated.  Do not under any circumstances grant the guest 
-- login access to the SQL Server!!! Currently the only object exposed to the 
-- guest USER is the dbo.InsEventLog sproc.  This may be independently verified
-- by creating a login with no explicit user permisisons in the new database and
-- logging is as that user and then by executing:
-- SELECT * FROM sys.objects
-- in the new database, only the dbo.InsEventLog sproc should be displayed.

--GRANT CONNECT TO guest
--GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AuditPackageExec]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[AuditPackageExec]
END
GO

CREATE TABLE [dbo].[AuditPackageExec](
     [AuditPackageExecId]      [int]          NOT NULL,
     [AuditPackageEnabledFlag] [tinyint]      NOT NULL DEFAULT ((1)),
     [AuditPackageName]        [varchar](128) NOT NULL,
     [AuditPackageLocation]    [varchar](30)  NOT NULL,
     [AuditPackagePath]        [varchar](255) NOT NULL,
     [EveryExecFlag]           [tinyint]      NOT NULL DEFAULT ((0)),
     [DailyExecFlag]           [tinyint]      NOT NULL DEFAULT ((0)),
     [MonthlyExecFlag]         [tinyint]      NOT NULL DEFAULT ((0)),
     [QuarterlyExecFlag]       [tinyint]      NOT NULL DEFAULT ((0)),
     CONSTRAINT [PK_AuditPackageExec] PRIMARY KEY CLUSTERED ( [AuditPackageExecId] ASC )
)
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique identifier of a particular Package Execution, also defines the order in which packages are executed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'AuditPackageExecId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this package execution is enabled.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'AuditPackageEnabledFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Package name not including *.dtsx.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'AuditPackageName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Physical location of package, "FILE SYSTEM" or "SQL SERVER".' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'AuditPackageLocation'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Path to the package, either file system or SQL server.  Includes full path, including *.dtsx for file system paths.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'AuditPackagePath'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this package should be run everytime the master package executor is run.  Regardless of other flags.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'EveryExecFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this package should be run daily.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'DailyExecFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this package should be run monthly.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'MonthlyExecFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this package should be run quarterly.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec', @level2type=N'COLUMN',@level2name=N'QuarterlyExecFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Data driven audit package execution control table.  Defines what packages are to be run for auditing and in what order.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AuditPackageExec'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CfgCtrl]') AND type in (N'U'))
BEGIN
     DROP TABLE dbo.CfgCtrl
END
GO

CREATE TABLE dbo.CfgCtrl(
     CfgCtrlKey         varchar(30)   NOT NULL,
     CfgCtrlValue       varchar(8000)     NULL,
     CfgCtrlDescription varchar(128)  NOT NULL,
     LastModDt          datetime      NOT NULL DEFAULT (getdate()),
     CONSTRAINT [PK_CfgCtrl] PRIMARY KEY CLUSTERED ( CfgCtrlKey ASC )
)
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Idenitifier of a particular Configuration Control Key.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CfgCtrl', @level2type=N'COLUMN',@level2name=N'CfgCtrlKey'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Value of the configuration control key.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CfgCtrl', @level2type=N'COLUMN',@level2name=N'CfgCtrlValue'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User-friendly description of the configuration control key.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CfgCtrl', @level2type=N'COLUMN',@level2name=N'CfgCtrlDescription'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CfgCtrl', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Database level configuration control data.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CfgCtrl'
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EventLog]') AND type in (N'U'))
BEGIN
     DROP TABLE dbo.EventLog
END
GO

CREATE TABLE dbo.EventLog(
     EventLogId        bigint IDENTITY(1,1) NOT NULL,
     EventLogTypeId    int NOT NULL,
     LogDt             datetime NOT NULL DEFAULT (getdate()),
     HostName          varchar(128) NOT NULL DEFAULT (host_name()),
     LoginName         varchar(128) NOT NULL DEFAULT (suser_sname()),
     DatabaseUserName  varchar(128) NULL DEFAULT (user_name()),
     DatabaseName      varchar(128) NULL DEFAULT (db_name()),
     AppName           varchar(128) NULL DEFAULT (app_name()),
     SPID              int NOT NULL DEFAULT (@@spid),
     [SID]             varbinary(85) NULL,
     LogByApp          varchar(128) NULL,
     LogByAppSubSystem varchar(128) NULL,
     LogByDesc         varchar(128) NULL,
     LogText           varchar(6144) NULL,
     TraceText         varchar(max) NULL,
     TraceImage        varbinary(max) NULL,
     MiscVC1           varchar(128) NULL,
     MiscVC2           varchar(128) NULL,
     MiscVC3           varchar(128) NULL,
     MiscVC4           varchar(128) NULL,
     MiscInt1          int NULL,
     MiscInt2          int NULL,
     MiscInt3          int NULL,
     MiscInt4          int NULL,
     MiscTinyint1      tinyint NULL,
     MiscTinyint2      tinyint NULL,
     MiscTinyint3      tinyint NULL,
     MiscTinyint4      tinyint NULL,
     MiscBigInt1       bigint NULL,
     MiscBigInt2       bigint NULL,
     MiscBigInt3       bigint NULL,
     MiscBigInt4       bigint NULL,
     MiscDt1           datetime NULL,
     MiscDt2           datetime NULL,
     MiscDt3           datetime NULL,
     MiscDt4           datetime NULL,
     MiscGUID1         uniqueidentifier NULL,
     MiscGUID2         uniqueidentifier NULL,
     MiscGUID3         uniqueidentifier NULL,
     MiscGUID4         uniqueidentifier NULL,
     CONSTRAINT PK_EventLog PRIMARY KEY CLUSTERED ( EventLogId ASC )
)
GO

CREATE NONCLUSTERED INDEX IX_EventLog_App_AppSubSystem_Desc ON dbo.EventLog 
     ( LogByApp ASC, LogByAppSubSystem ASC, LogByDesc ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_AppName ON dbo.EventLog ( AppName ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_DatabaseName ON dbo.EventLog ( DatabaseName ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_EventLogTypeId ON dbo.EventLog ( EventLogTypeId ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_HostName ON dbo.EventLog ( HostName ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_LogDt ON dbo.EventLog ( LogDt ASC )
GO

CREATE NONCLUSTERED INDEX IX_EventLog_LoginName ON dbo.EventLog ( LoginName ASC )
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log entry.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'EventLogId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'EventLogTypeId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date/time when event was logged.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LogDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Host Name of logged activity.  Caution!  Is not set by system therefore can be spoofed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'HostName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server login name of logged event.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LoginName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Username in the database of logged event.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'DatabaseUserName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Database name where activity was logged into.  For single application use will usually match database of application, for server level use will usually match database of calling application.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'DatabaseName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Application Name of logged activity.  Caution!  Is not set by system therefore can be spoofed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'AppName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server Process Id of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'SPID'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'SID of user of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'SID'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LogByApp'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application Sub-System.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LogByAppSubSystem'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application Description, usually additional additional detail such as sub-sub-process, or internal identifier.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LogByDesc'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Log message of the logged activity.  6K Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'LogText'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Traced text of logged activity.  2GB Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'TraceText'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Traced binary image of logged activity.  2GB Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'TraceImage'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscVC1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscVC2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscVC3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscVC4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscInt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscInt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscInt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscInt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscDt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscDt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscDt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscDt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event logging.  Contains logged events.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLog'
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EventLogType]') AND type in (N'U'))
BEGIN
     DROP TABLE dbo.EventLogType
END
GO

CREATE TABLE dbo.EventLogType(
     EventLogTypeId   int         NOT NULL,
     EventLogTypeCd   varchar(5)  NOT NULL,
     EventLogTypeDesc varchar(15) NOT NULL,
     CONSTRAINT PK_EventLogType PRIMARY KEY CLUSTERED ( EventLogTypeId ASC )
)
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_EventLogType_EventLogTypeCd] ON [dbo].[EventLogType] ([EventLogTypeCd])
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Secondary Unique Identifier of a particular Event Log Type, user defined.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeCd'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Description of Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeDesc'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event logging types.  Contains list of event log types, normally: Unknown(0), Informational(1), Warning(2), and Error(3).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EventLogType'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Machine]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[Machine]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Machine](
     [MachineId]              [int] IDENTITY(1,1) NOT NULL,
     [PackageExecutionId]     [bigint]            NOT NULL,
     [EnabledFlag]            [tinyint]           NOT NULL CONSTRAINT [DF_Machine_EnabledFlag]  DEFAULT ((1)),
     [MachineName]            [varchar](128)      NOT NULL,
     [FQMachineName]          [varchar](255)      NOT NULL,
     [PhysicalCPUCount]       [int]                   NULL,
     [PhysicalCPUCoreCount]   [int]                   NULL,
     [LogicalCPUCoreCount]    [int]                   NULL,
     [MaxCPUSpeedMHz]         [int]                   NULL,
     [OSVersion]              [varchar](30)           NULL,
     [OSLevel]                [varchar](30)           NULL,
     [OSArchitecture]         [varchar](10)           NULL,
     [OSEdition]              [varchar](128)          NULL,
     [TotalMachineMemoryMB]   [int]                   NULL,
     [RSVDMachineMemoryMB]    [int]                   NULL,
     [ClusterVirtualNameFlag] [tinyint]           NOT NULL CONSTRAINT [DF_Machine_ClusterVirtualNameFlag] DEFAULT ((0)),
     [LastModDt]              [datetime]          NOT NULL CONSTRAINT [DF_Machine_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_Machine] PRIMARY KEY CLUSTERED ( [MachineId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Machine] WITH CHECK ADD CONSTRAINT [CK_Machine_RSVD] CHECK (([RSVDMachineMemoryMB]>=(512) AND [RSVDMachineMemoryMB]<[TotalMachineMemoryMB]))
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_Machine_Name] ON [dbo].[Machine] ( [MachineName] ASC ) ON [Data_Index]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MachineCluster]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MachineCluster]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[MachineCluster](
     [ClusterMachineId]   [int]      NOT NULL,
     [MemberMachineId]    [int]      NOT NULL,
     [PackageExecutionId] [bigint]   NOT NULL,
     [LastModDt]          [datetime] NOT NULL CONSTRAINT [DF_MachineCluster_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_MachineCluster] PRIMARY KEY CLUSTERED ( [ClusterMachineId] ASC, [MemberMachineId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MachineDriveVolume]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MachineDriveVolume]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[MachineDriveVolume](
     [MachineId]               [int]          NOT NULL,
     [MachineDriveVolumeId]    [int]          NOT NULL,
     [StartDt]                 [datetime]     NOT NULL,
     [EndDt]                   [datetime]     NOT NULL,
     [CurrentRecordFlag]       [tinyint]      NOT NULL,
     [PackageExecutionId]      [bigint]       NOT NULL,
     [VolumeDeletedFlag]       [tinyint]      NOT NULL,
     [VolumeDeviceId]          [varchar](128) NOT NULL,
     [VolumeMountPoint]        [varchar](255)     NULL,
     [VolumeBlockSize]         [int]              NULL,
     [VolumeCapacity]          [bigint]           NULL,
     [VolumeCompressedFlag]    [tinyint]          NULL,
     [VolumeDriveTypeDesc]     [varchar](30)  NOT NULL,
     [VolumeFileSystemType]    [varchar](6)   NOT NULL,
     [VolumeLabel]             [varchar](32)  NOT NULL,
     [VolumeName]              [varchar](128) NOT NULL,
     [VolumeSerialNumber]      [bigint]       NOT NULL,
     [ClusterSharedVolumeFlag] [tinyint]      NOT NULL,
     CONSTRAINT [PK_MachineDriveVolume] PRIMARY KEY CLUSTERED ( [MachineId] ASC, [MachineDriveVolumeId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MachineDriveVolumeSpace]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MachineDriveVolumeSpace]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[MachineDriveVolumeSpace](
     [MachineId]                   [int]      NOT NULL,
     [MachineDriveVolumeId]        [int]      NOT NULL,
     [CaptureDt]                   [datetime] NOT NULL,
     [PackageExecutionId]          [bigint]   NOT NULL,
     [VolumeCapacityBytes]         [bigint]   NOT NULL,
     [VolumeFreeSpaceBytes]        [bigint]   NOT NULL,
     [VolumeUsedSpaceBytes]  AS ([VolumeCapacityBytes]-[VolumeFreeSpaceBytes]) PERSISTED,
     [VolumeCapacityKBytes]  AS ([VolumeCapacityBytes]/(1024)) PERSISTED,
     [VolumeFreeSpaceKBytes]  AS ([VolumeFreeSpaceBytes]/(1024)) PERSISTED,
     [VolumeUsedSpaceKBytes]  AS (([VolumeCapacityBytes]-[VolumeFreeSpaceBytes])/(1024)) PERSISTED,
     [VolumeFreeSpacePCT]  AS (CONVERT([decimal](7,4),(CONVERT([decimal](38,5),[VolumeFreeSpaceBytes],0)/CONVERT([decimal](38,5),[VolumeCapacityBytes],0))*(100),0)) PERSISTED,
     [VolumeUsedSpacePCT]  AS (CONVERT([decimal](7,4),(CONVERT([decimal](38,5),[VolumeCapacityBytes]-[VolumeFreeSpaceBytes],0)/CONVERT([decimal](38,5),[VolumeCapacityBytes],0))*(100),0)) PERSISTED
     [FreeSpaceOutsideTolerance]   [tinyint]      NULL,
     [FreeSpaceAlertGeneratedFlag] [tinyint]      NULL,
     CONSTRAINT [PK_MachineDriveVolumeSpace] PRIMARY KEY CLUSTERED ( [MachineId] ASC, [MachineDriveVolumeId] ASC, [CaptureDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MachineEnvVar]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MachineEnvVar]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[MachineEnvVar](
     [MachineId]          [int]           NOT NULL,
     [MachineEnvVarId]    [int]           NOT NULL,
     [StartDt]            [datetime]      NOT NULL,
     [EndDt]              [datetime]      NOT NULL,
     [CurrentRecordFlag]  [tinyint]       NOT NULL CONSTRAINT [DF_MachineEnvVar_CurrentRecordFlag]  DEFAULT ((0)),
     [PackageExecutionId] [bigint]        NOT NULL,
     [VarDeletedFlag]     [tinyint]       NOT NULL,
     [VarName]            [varchar](100)  NOT NULL,
     [VarUser]            [varchar](128)  NOT NULL,
     [VarVal]             [varchar](7680)     NULL,
     CONSTRAINT [PK_MachineEnvVar] PRIMARY KEY CLUSTERED ( [MachineId] ASC, [MachineEnvVarId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MachineMSInstalledComponents]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MachineMSInstalledComponents]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[MachineMSInstalledComponents](
     [MachineMSInstalledComponentsId] [int] IDENTITY(1,1) NOT NULL,
     [MachineId]                      [int]               NOT NULL,
     [PackageExecutionId]             [bigint]            NOT NULL,
     [ServiceName]                    [varchar](128)      NOT NULL,
     [InstanceName]                   [varchar](128)      NOT NULL,
     [InstalledComponentName]         [varchar](30)       NOT NULL,
     [IsClusteredFlag]                [tinyint]           NOT NULL,
     [SrvrInstncId]                   [int]                   NULL,
     [RelatedToSrvrInstncId]          [int]                   NULL,
     [InstalledComponentDeletedFlag]  [tinyint]           NOT NULL,
     [LastModDt]                      [datetime]          NOT NULL,
     CONSTRAINT [PK_MachineMSInstalledComponents] PRIMARY KEY CLUSTERED ( [MachineMSInstalledComponentsId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_MachineMSInstalledComponents_MachineId_ServiceName] ON [dbo].[MachineMSInstalledComponents] 
     ( [MachineId] ASC, [ServiceName] ASC ) ON [Data_Index]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MachineMSInstalledComponents', @level2type=N'COLUMN',@level2name=N'InstalledComponentDeletedFlag'
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MasterEventLog_MasterEventLogType]') AND parent_object_id = OBJECT_ID(N'[dbo].[MasterEventLog]'))
BEGIN
     ALTER TABLE [dbo].[MasterEventLog] DROP CONSTRAINT [FK_MasterEventLog_MasterEventLogType]
END
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MasterEventLog_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[MasterEventLog]'))
BEGIN
     ALTER TABLE [dbo].[MasterEventLog] DROP CONSTRAINT [FK_MasterEventLog_SrvrInstnc]
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterEventLog]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MasterEventLog]
END
GO

CREATE TABLE [dbo].[MasterEventLog](
     [SrvrInstncDatabaseId] [int]              NOT NULL,
     [EventLogId]           [bigint]           NOT NULL,
     [RecordGUID]           [uniqueidentifier] NOT NULL,
     [EventLogTypeId]       [int]              NOT NULL,
     [LogDt]                [datetime]         NOT NULL,
     [HostName]             [varchar](128)     NOT NULL,
     [LoginName]            [varchar](128)     NOT NULL,
     [DatabaseUserName]     [varchar](128)         NULL,
     [DatabaseName]         [varchar](128)         NULL,
     [AppName]              [varchar](128)         NULL,
     [SPID]                 [int]              NOT NULL,
     [SID]                  [varbinary](85)        NULL,
     [LogByApp]             [varchar](128)         NULL,
     [LogByAppSubSystem]    [varchar](128)         NULL,
     [LogByDesc]            [varchar](128)         NULL,
     [LogText]              [varchar](6144)        NULL,
     [TraceText]            [varchar](max)         NULL,
     [TraceImage]           [varbinary](max)       NULL,
     [MiscVC1]              [varchar](128)         NULL,
     [MiscVC2]              [varchar](128)         NULL,
     [MiscVC3]              [varchar](128)         NULL,
     [MiscVC4]              [varchar](128)         NULL,
     [MiscInt1]             [int]                  NULL,
     [MiscInt2]             [int]                  NULL,
     [MiscInt3]             [int]                  NULL,
     [MiscInt4]             [int]                  NULL,
     [MiscTinyint1]         [tinyint]              NULL,
     [MiscTinyint2]         [tinyint]              NULL,
     [MiscTinyint3]         [tinyint]              NULL,
     [MiscTinyint4]         [tinyint]              NULL,
     [MiscBigInt1]          [bigint]               NULL,
     [MiscBigInt2]          [bigint]               NULL,
     [MiscBigInt3]          [bigint]               NULL,
     [MiscBigInt4]          [bigint]               NULL,
     [MiscDt1]              [datetime]             NULL,
     [MiscDt2]              [datetime]             NULL,
     [MiscDt3]              [datetime]             NULL,
     [MiscDt4]              [datetime]             NULL,
     [MiscGUID1]            [uniqueidentifier]     NULL,
     [MiscGUID2]            [uniqueidentifier]     NULL,
     [MiscGUID3]            [uniqueidentifier]     NULL,
     [MiscGUID4]            [uniqueidentifier]     NULL,
     [PackageExecutionId]   [bigint]               NULL,
     CONSTRAINT [PK_MasterEventLog] PRIMARY KEY CLUSTERED 
          ( [SrvrInstncDatabaseId] ASC, [EventLogId] ASC )
) TEXTIMAGE_ON Data_BLOB
GO

-- Determine SQL Version to determine which default value will be used for RecordId
-- SQL 2005 does not support newsequentialid() so newid() will be used in 2005, but
-- newsequentialid() will be used for later versions.  We also don't test for 
-- SQL 2000 since there are a number of datatypes in the table above that could not
-- be used in SQL 2000.
DECLARE @PV varchar(30),
        @V  int

SET @PV = CONVERT( varchar(30), SERVERPROPERTY('ProductVersion') )

SELECT @V = SUBSTRING(@PV,1, CHARINDEX('.',@PV) -1 )

IF ( @V = 9 )
BEGIN -- SQL 2005
     EXEC ( 'ALTER TABLE [dbo].[MasterEventLog] ADD CONSTRAINT [DF_MasterEventLog_RecordGUID] DEFAULT (newid()) FOR [RecordGUID]' )
END
ELSE
BEGIN -- SQL 2008 + 
     EXEC ( 'ALTER TABLE [dbo].[MasterEventLog] ADD CONSTRAINT [DF_MasterEventLog_RecordGUID] DEFAULT (newsequentialid()) FOR [RecordGUID]' )
END
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_App_AppSubSystem_Desc] ON [dbo].[MasterEventLog] 
     ( [LogByApp] ASC, [LogByAppSubSystem] ASC, [LogByDesc] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_AppName] ON [dbo].[MasterEventLog] 
     ( [AppName] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_DatabaseName] ON [dbo].[MasterEventLog] 
     ( [DatabaseName] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_EventLogTypeId] ON [dbo].[MasterEventLog] 
     ( [EventLogTypeId] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_HostName] ON [dbo].[MasterEventLog] 
     ( [HostName] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_LogDt] ON [dbo].[MasterEventLog] 
     ( [LogDt] ASC )
GO

CREATE NONCLUSTERED INDEX [IX_MasterEventLog_LoginName] ON [dbo].[MasterEventLog] 
     ( [LoginName] ASC )
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_MasterEventLog_RecordGUID] ON [dbo].[MasterEventLog] 
     ( [RecordGUID] ASC )
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database on a Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'SrvrInstncDatabaseId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log entry.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'EventLogId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique identifier of this particular logged entry.  This is used to uniquely identify this record without a composite key, this can be used for a FT index key.  Is a newid in SQL 2005, and a newsequentialid in SQL 2008.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'RecordGUID'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'EventLogTypeId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date/time when event was logged.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LogDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Host Name of logged activity.  Caution!  Is not set by system therefore can be spoofed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'HostName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server login name of logged event.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LoginName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Username in the database of logged event.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'DatabaseUserName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Database name where activity was logged into.  For single application use will usually match database of application, for server level use will usually match database of calling application.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'DatabaseName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Application Name of logged activity.  Caution!  Is not set by system therefore can be spoofed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'AppName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server Process Id of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'SPID'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'SID of user of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'SID'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LogByApp'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application Sub-System.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LogByAppSubSystem'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Event Logged by Application Description, usually additional additional detail such as sub-sub-process, or internal identifier.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LogByDesc'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Log message of the logged activity.  6K Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'LogText'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Traced text of logged activity.  2GB Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'TraceText'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Traced binary image of logged activity.  2GB Max.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'TraceImage'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscVC1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscVC2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscVC3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc varchar(128) 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscVC4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscInt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscInt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscInt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc int 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscInt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc tinyint 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscTinyint4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc bigint 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscBigInt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscDt1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscDt2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscDt3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc datetime 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscDt4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 1 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID1'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 2 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID2'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 3 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID3'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Misc GUID 4 of logged activity.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'MiscGUID4'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Combined event logging.  Contains combined EventLog tables from one or more server instances and databases.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLog'
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MasterEventLogType_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[MasterEventLogType]'))
BEGIN
     ALTER TABLE [dbo].[MasterEventLogType] DROP CONSTRAINT [FK_MasterEventLogType_SrvrInstnc]
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterEventLogType]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[MasterEventLogType]
END
GO

CREATE TABLE [dbo].[MasterEventLogType](
     [SrvrInstncDatabaseId] [int]         NOT NULL,
     [EventLogTypeId]       [int]         NOT NULL,
     [EventLogTypeCd]       [varchar](5)  NOT NULL,
     [EventLogTypeDesc]     [varchar](15) NOT NULL,
     CONSTRAINT [PK_MasterEventLogType] PRIMARY KEY CLUSTERED 
          ( [SrvrInstncDatabaseId] ASC, [EventLogTypeId] ASC )
)
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_MasterEventLogType_EventLogTypeCd] ON [dbo].[MasterEventLogType] 
     ( [SrvrInstncDatabaseId] ASC, [EventLogTypeCd] ASC )
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database on a Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLogType', @level2type=N'COLUMN',@level2name=N'SrvrInstncDatabaseId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Secondary Unique Identifier of a particular Event Log Type, user defined.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeCd'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Description of Event Log Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLogType', @level2type=N'COLUMN',@level2name=N'EventLogTypeDesc'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Combined event logging types.  Contains list of event log types from one or more server instance databases.  Normally matches delivered 4 items per server instance database.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MasterEventLogType'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Parameter]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[Parameter]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Parameter](
     [ParameterId]           [int]          NOT NULL,
     [ParameterCd]           [varchar](30)  NOT NULL,
     [ParameterName]         [varchar](128) NOT NULL,
     [ParameterDefaultValue] [varchar](256)     NULL,
     [ParamAllowMutliFlag]   [tinyint]      NOT NULL CONSTRAINT [DF_Parameter_ParamAllowMutliFlag]  DEFAULT ((0)),
     [ParamMaxMultiCnt]      [int]          NOT NULL CONSTRAINT [DF_Parameter_ParamMaxMutliFlag]  DEFAULT ((0)),
     [LastModDt]             [datetime]     NOT NULL CONSTRAINT [DF_Parameter_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_Parameter] PRIMARY KEY CLUSTERED ( [ParameterId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_Parameter_Code] ON [dbo].[Parameter] 
     ( [ParameterCd] ASC ) ON [Data_Index]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Parameter.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParameterId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Secondary Unique Identifier of a particular Parameter, user defined.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParameterCd'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User-friendly name of parameter.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParameterName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Default value of parameter when added to EAV table.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParameterDefaultValue'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether multiple records of this parameter type are allowed, also defines whether to look in the EAV or EAVMulti table for the parameter.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParamAllowMutliFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Maximum number of multiple records if allowed.  If not allowed then this value is ignored, zero indicates no limit.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'ParamMaxMultiCnt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Parameters.  Contains master parameter list and basic parameter control data.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Parameter'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Seq]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[Seq]
END
GO

CREATE TABLE [dbo].[Seq](
	[SeqName]   [varchar](128) NOT NULL,
	[SeqNumber] [bigint] NOT NULL,
     CONSTRAINT [PK_Seq] PRIMARY KEY CLUSTERED ( [SeqName] ASC )
)
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Sequence Name.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Seq', @level2type=N'COLUMN',@level2name=N'SeqName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Value of the Sequence Name.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Seq', @level2type=N'COLUMN',@level2name=N'SeqNumber'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Contains records for application controlled id values.  Effectively application controlled identity values.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Seq'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstnc]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstnc]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstnc](
     [SrvrInstncId]       [int] IDENTITY(1,1) NOT NULL,
     [SrvrInstncTypeId]   [int]               NOT NULL,
     [SrvrInstncGrpId]    [int]               NOT NULL CONSTRAINT [DF_SrvrInstnc_SrvrInstncGrpId] DEFAULT ((1)),
     [EnabledFlag]        [tinyint]           NOT NULL CONSTRAINT [DF_SrvrInstnc_EnabledFlag] DEFAULT ((1)),
     [SrvrInstncFullName] [varchar](255)      NOT NULL,
     [LastModDt]          [datetime]          NOT NULL CONSTRAINT [DF_SrvrInstnc_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstance] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncAlias]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncAlias]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncAlias](
     [SrvrInstncId]       [int]          NOT NULL,
     [SrvrInstncFullName] [varchar](255) NOT NULL,
     [DoNotUseFlag]       [tinyint]      NOT NULL CONSTRAINT [DF_SrvrInstncAlias_DoNotUseFlag] DEFAULT ((0)),
     [LastModDt]          [datetime]     NOT NULL CONSTRAINT [DF_SrvrInstncAlias_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncAlias] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [SrvrInstncFullName] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncCfg1MSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncCfg1MSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncCfg1MSSQL](
     [SrvrInstncId]               [int]          NOT NULL,
     [PackageExecutionId]         [int]          NOT NULL,
     [StartDt]                    [datetime]     NOT NULL,
     [EndDt]                      [datetime]     NOT NULL,
     [CurrentRecordFlag]          [tinyint]      NOT NULL CONSTRAINT [DF_SrvrInstncCfg1MSSQL_CurrentRecordFlag]  DEFAULT ((0)),
     [ClusteredFlag]              [tinyint]          NULL,
     [FullTextInstalledFlag]      [tinyint]          NULL,
     [IntegratedSecurityOnlyFlag] [tinyint]          NULL,
     [ProductVersion]             [varchar](30)      NULL,
     [ProductLevel]               [varchar](30)      NULL,
     [ProductArchitecture]        [varchar](6)       NULL,
     [ServerEdition]              [varchar](128)     NULL,
     [LicenseType]                [varchar](30)      NULL,
     [NumberOfLicenses]           [int]              NULL,
     [SrvrCollation]              [varchar](128)     NULL,
     [SrvrMinMemoryMB]            [int]              NULL,
     [SrvrMaxMemoryMB]            [int]              NULL,
     [LastModDt]                  [datetime]     NOT NULL CONSTRAINT [DF_SrvrInstncCfg1MSSQL_LastModDt]  DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncCfg1MSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'SrvrInstncId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective start date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'StartDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective end date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'EndDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this record is the current record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'CurrentRecordFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether server is clustered.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'ClusteredFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether the full-text server is installed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'FullTextInstalledFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether server is configured for integrated security only.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'IntegratedSecurityOnlyFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Version of the SQL Server.  For MSSQL often expressed as: major.minor.build' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'ProductVersion'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Level of the version of the SQL Server.  For MSSQL often expressed as: RTM, SP1, SP2, CTP' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'ProductLevel'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Edition of the SQL Server.  For MSSQL often expressed as: Standard Edition, Enterprise Edition' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'ServerEdition'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Type of server license, often disabled.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'LicenseType'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Number of licensed CALs whether processor or client.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'NumberOfLicenses'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Default Collation of the SQL Server.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'SrvrCollation'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Minimum configured server memory in MB.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'SrvrMinMemoryMB'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Maximum configured server memory in MB.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL', @level2type=N'COLUMN',@level2name=N'SrvrMaxMemoryMB'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance configuration data for MSSQL Servers.  Contains effective dated list of server instance configuration data for a MSSQL type server.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg1MSSQL'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncCfg2MSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncCfg2MSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncCfg2MSSQL](
     [SrvrInstncId]         [int]          NOT NULL,
     [PackageExecutionId]   [int]          NOT NULL,
     [StartDt]              [datetime]     NOT NULL,
     [EndDt]                [datetime]     NOT NULL,
     [CurrentRecordFlag]    [tinyint]      NOT NULL CONSTRAINT [DF_SrvrInstncCfg2MSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [SysConfigurationId]   [int]          NOT NULL,
     [SysConfigurationName] [varchar](255) NOT NULL,
     [ConfigValue]          [bigint]       NOT NULL,
     [RunValue]             [bigint]       NOT NULL,
     CONSTRAINT [PK_SrvrInstncCfg2MSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [StartDt] ASC, [SysConfigurationId] ASC ) 
)
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL', @level2type=N'COLUMN',@level2name=N'SrvrInstncId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective start date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL', @level2type=N'COLUMN',@level2name=N'StartDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective end date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL', @level2type=N'COLUMN',@level2name=N'EndDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this record is the current record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL', @level2type=N'COLUMN',@level2name=N'CurrentRecordFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance configuration data for MSSQL Servers.  Contains effective dated list of server instance configuration data for a MSSQL type server.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncCfg2MSSQL'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabase]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncDatabase]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncDatabase](
     [SrvrInstncDatabaseId] [int] IDENTITY(1,1) NOT NULL,
     [SrvrInstncId]         [int]               NOT NULL,
     [PackageExecutionId]   [bigint]            NOT NULL,
     [DatabaseName]         [varchar](128)      NOT NULL,
     [EnabledFlag]          [tinyint]           NOT NULL CONSTRAINT [DF_SrvrInstncDatabase_EnabledFlag] DEFAULT ((0)),
     [LastModDt]            [datetime]          NOT NULL CONSTRAINT [DF_SrvrInstncDatabase_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncDatabase] PRIMARY KEY CLUSTERED ( [SrvrInstncDatabaseId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_SrvrInstncDatabase_ServerKey] ON [dbo].[SrvrInstncDatabase] 
     ( [SrvrInstncId] ASC, [DatabaseName] ASC ) ON [Data_Index]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database on a Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase', @level2type=N'COLUMN',@level2name=N'SrvrInstncDatabaseId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase', @level2type=N'COLUMN',@level2name=N'SrvrInstncId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Name of the database.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase', @level2type=N'COLUMN',@level2name=N'DatabaseName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database has been deleted,' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase', @level2type=N'COLUMN',@level2name=N'EnabledFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance databases.  Contains effective dated list of all databases and database history for a server instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabase'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabaseFileMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncDatabaseFileMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncDatabaseFileMSSQL](
     [SrvrInstncDatabaseFileMSSQLId] [int]              NOT NULL,
     [SrvrInstncDatabaseId]          [int]              NOT NULL,
     [PackageExecutionId]            [bigint]           NOT NULL,
     [StartDt]                       [datetime]         NOT NULL,
     [EndDt]                         [datetime]         NOT NULL,
     [CurrentRecordFlag]             [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncDatabaseFileMSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [FileDeletedFlag]               [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncDatabaseFileMSSQL_FileDeletedFlag] DEFAULT ((0)),
     [DatabaseFileId]                [int]                  NULL,
     [DatabaseFileGUID]              [uniqueidentifier]     NULL,
     [FileIsLogFileFlag]             [tinyint]              NULL,
     [FileSizeInMB]                  [int]              NOT NULL,
     [MaxFileSizeInMB]               [int]                  NULL,
     [FileGrowthInMB]                [int]                  NULL,
     [FileGrowthInPct]               [tinyint]              NULL,
     [FileGroupName]                 [varchar](128)         NULL,
     [LogicalFileName]               [varchar](128)         NULL,
     [PhysicalFileNameWithPath]      [varchar](255)         NULL,
     CONSTRAINT [PK_SrvrInstncDatabaseFileMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncDatabaseFileMSSQLId] ASC, [SrvrInstncDatabaseId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabaseMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncDatabaseMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncDatabaseMSSQL](
     [SrvrInstncDatabaseId]     [int]          NOT NULL,
     [PackageExecutionId]       [bigint]       NOT NULL,
     [StartDt]                  [datetime]     NOT NULL,
     [EndDt]                    [datetime]     NOT NULL,
     [CurrentRecordFlag]        [tinyint]      NOT NULL CONSTRAINT [DF_SrvrInstncDatabaseMSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [DatabaseDeletedFlag]      [tinyint]      NOT NULL CONSTRAINT [DF_SrvrInstncDatabaseMSSQL_DatabaseDeletedFlag]  DEFAULT ((0)),
     [DatabaseId]               [int]              NULL,
     [DatabaseOwnerName]        [varchar](128)     NULL,
     [DateCreated]              [datetime]         NULL,
     [DatabaseReadOnlyFlag]     [tinyint]          NULL,
     [CompatibilityLevel]       [varchar](10)      NULL,
     [Collation]                [varchar](128)     NULL,
     [DBStatus]                 [varchar](30)      NULL,
     [RecoveryModel]            [varchar](15)      NULL,
     [AccessLevel]              [varchar](30)      NULL,
     [AutoCloseFlag]            [tinyint]          NULL,
     [AutoCreateStatsFlag]      [tinyint]          NULL,
     [AutoShrinkFlag]           [tinyint]          NULL,
     [AutoUpdateStatsFlag]      [tinyint]          NULL,
     [AutoUpdateStatsAsyncFlag] [tinyint]          NULL,
     [RecursiveTriggersFlag]    [tinyint]          NULL,
     [TrustworthyFlag]          [tinyint]          NULL,
     [BrokerEnabledFlag]        [tinyint]          NULL,
     [EncryptionFlag]           [tinyint]          NULL,
     CONSTRAINT [PK_SrvrInstncDatabaseMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncDatabaseId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database on a Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'SrvrInstncDatabaseId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective start date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'StartDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Effective end date of this record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'EndDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this record is the current record.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'CurrentRecordFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database has been deleted,' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DatabaseDeletedFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Database Id from the server.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DatabaseId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Owner name of the database.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DatabaseOwnerName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date/time the database created.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DateCreated'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for read-only.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DatabaseReadOnlyFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Compatibility level of the database.  Currently: 80, 90, 100' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'CompatibilityLevel'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Collation of the database.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'Collation'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Status of the database.  Usually: ONLINE, OFFLINE, RESTORING, RECOVERING, SUSPECT, EMERGENCY' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'DBStatus'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Recover model of the database.  Usually: FULL, BULK_LOGGED, SIMPLE' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'RecoveryModel'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Access level of the database.  Usually: SINGLE_USER, RESTRICTED_USER, MULTI_USER' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AccessLevel'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Auto Close.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AutoCloseFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Auto Create Statistics.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AutoCreateStatsFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Auto Shrink.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AutoShrinkFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Auto Update Statistics.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AutoUpdateStatsFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Auto Update Statistics Asynchronously.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'AutoUpdateStatsAsyncFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set for Recursive Triggers.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'RecursiveTriggersFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is set as Trustworthy.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'TrustworthyFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database is enabled for service broken.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'BrokerEnabledFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating whether this database has encryption enabled.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL', @level2type=N'COLUMN',@level2name=N'EncryptionFlag'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instnace databases.  Contains effective dated list of all databases and database history for a server instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseMSSQL'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabaseSize]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncDatabaseSize]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncDatabaseSize](
     [SrvrInstncDatabaseId]   [int]      NOT NULL,
     [PackageExecutionId]     [bigint]   NOT NULL,
     [CaptureDt]              [datetime] NOT NULL,
     [CurrentRecordForDtFlag] [tinyint]  NOT NULL CONSTRAINT [DF_SrvrInstncDatabaseSize_CurrentRecordForDtFlag] DEFAULT ((0)),
     [TotalDataSpaceMB]       [int]      NOT NULL,
     [TotalDataFiles]         [int]      NOT NULL,
     [TotalLogSpaceMB]        [int]      NOT NULL,
     [TotalLogFiles]          [int]      NOT NULL,
     [CollectionDateOnly]  AS (dateadd(day,datediff(day,(0),[CaptureDt]),(0))) PERSISTED,
     CONSTRAINT [PK_SrvrInstncDatabaseSize] PRIMARY KEY CLUSTERED ( [SrvrInstncDatabaseId] ASC, [CaptureDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date/time sample was collected.  Use CollectionDateOnly for reporting.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseSize', @level2type=N'COLUMN',@level2name=N'CaptureDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Flag indicating that this record is the most current record for a specified collection date.  This field should be used for recporting on a specific date, records that are zero should be ignored.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncDatabaseSize', @level2type=N'COLUMN',@level2name=N'CurrentRecordForDtFlag'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncEAV]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncEAV]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncEAV](
     [SrvrInstncId]     [int]           NOT NULL,
     [ParameterId]      [int]           NOT NULL,
     [ParameterMultiId] [int]           NOT NULL CONSTRAINT [DF_SrvrInstncEAV_ParameterMultiId] DEFAULT ((0)),
     [ParameterValue]   [varchar](8000)     NULL,
     [LastModDt]        [datetime]      NOT NULL CONSTRAINT [DF_SrvrInstncEAV_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncEAV] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [ParameterId] ASC, [ParameterMultiId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV', @level2type=N'COLUMN',@level2name=N'SrvrInstncId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Parameter.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV', @level2type=N'COLUMN',@level2name=N'ParameterId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular record for the specified database server instance and parameter.  This is used to make the record unique.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV', @level2type=N'COLUMN',@level2name=N'ParameterMultiId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Value of the parameter for the specified database server instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV', @level2type=N'COLUMN',@level2name=N'ParameterValue'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance Entity-Attribute-Values for multiple entries per parameter and server instance if.  Contains key-value pairs for a particular server instance id but allows more than one value for a parameter to be stored.  Use of this table is controlled by whether a parameter allows multiple values to be stored.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncEAV'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncGrp]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncGrp]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncGrp](
     [SrvrInstncGrpId]       [int]         NOT NULL,
     [SrvrInstncGrpPriority] [tinyint]     NOT NULL CONSTRAINT [DF_SrvrInstncGrp_SrvrInstncGrpPriority] DEFAULT ((0)),
     [SrvrInstncGrpName]     [varchar](80) NOT NULL,
     [LastModDt]             [datetime]    NOT NULL CONSTRAINT [DF_SrvrInstncGrp_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncGrp] PRIMARY KEY CLUSTERED ( [SrvrInstncGrpId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_SrvrInstncGrp_Priority] ON [dbo].[SrvrInstncGrp] 
     ( [SrvrInstncGrpPriority] ASC ) ON [Data_Index]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Server Instance Group.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncGrp', @level2type=N'COLUMN',@level2name=N'SrvrInstncGrpId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Priority relative to other groups, if more than one group shares the same value there is no way to predict which group will take priority.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncGrp', @level2type=N'COLUMN',@level2name=N'SrvrInstncGrpPriority'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User-friendly description of the Server Instance Group.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncGrp', @level2type=N'COLUMN',@level2name=N'SrvrInstncGrpName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncGrp', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance groupings.  Contains master list of server groupings, and controls priority of order in execution of servers during audit and collection processes.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncGrp'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncMachine]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncMachine]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncMachine](
     [SrvrInstncId]       [int]      NOT NULL,
     [MachineId]          [int]      NOT NULL,
     [PackageExecutionId] [bigint]   NOT NULL,
     [LastModDt]          [datetime] NOT NULL CONSTRAINT [DF_SrvrInstncMachine_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncMachine] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [MachineId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Database Server Instance.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncMachine', @level2type=N'COLUMN',@level2name=N'SrvrInstncId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular server machine.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncMachine', @level2type=N'COLUMN',@level2name=N'MachineId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Execution Id of the package that populated or updated this row (usually by SSIS).' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncMachine', @level2type=N'COLUMN',@level2name=N'PackageExecutionId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncMachine', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance machines.  Contains the linkake between server instances and server machines.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncMachine'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncMemoryCfgMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncMemoryCfgMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncMemoryCfgMSSQL](
     [SrvrInstncId] [int]          NOT NULL,
     [MemoryShare]  [decimal](5,1) NOT NULL,
     [LastModDt]    [datetime]     NOT NULL CONSTRAINT [DF_SrvrInstncMemoryCfgMSSQL_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncMemoryCfgMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncMSSQL](
     [SrvrInstncId]           [int]          NOT NULL,
     [SrvrInstncMachineName]  [varchar](128) NOT NULL,
     [SrvrInstncInstanceName] [varchar](128) NOT NULL,
     CONSTRAINT [PK_SrvrInstncMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncSchedJobHistoryMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncSchedJobHistoryMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncSchedJobHistoryMSSQL](
     [SrvrInstncId]              [int]           NOT NULL,
     [JobHistoryId]              [int]           NOT NULL,
     [PackageExecutionId]        [bigint]        NOT NULL,
     [SrvrInstncSchedJobId]      [int]           NOT NULL,
     [JobStepId]                 [int]           NOT NULL,
     [JobStepName]               [varchar](128)  NOT NULL,
     [JobStepMessage]            [varchar](4000)     NULL,
     [JobRunStatus]              [varchar](15)   NOT NULL,
     [JobRunDt]                  [datetime]      NOT NULL,
     [JobRunDurationInSec]       [int]           NOT NULL,
     [OperatorEmailed]           [varchar](128)  NOT NULL,
     [OperatorPaged]             [varchar](128)  NOT NULL,
     [OperatorNetSent]           [varchar](128)  NOT NULL,
     [RetriesAttempted]          [int]           NOT NULL,
     [JobStartMethod]            [varchar](15)   NOT NULL,
     [JobExecutedOnSrvrInstncId] [int]               NULL,
     [JobExecutedOnServer]       [varchar](128)      NULL,
     CONSTRAINT [PK_SrvrInstncSchedJobHistoryMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [JobHistoryId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_SrvrInstncSchedJobHistoryMSSQL_SecondaryKey] ON [dbo].[SrvrInstncSchedJobHistoryMSSQL] 
     ( [SrvrInstncId] ASC, [SrvrInstncSchedJobId] ASC, [JobHistoryId] ASC ) ON [Data_Index]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncSchedJobMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncSchedJobMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncSchedJobMSSQL](
     [SrvrInstncId] [int] NOT NULL,
     [SrvrInstncSchedJobId] [int] NOT NULL,
     [StartDt] [datetime] NOT NULL,
     [EndDt] [datetime] NOT NULL,
     [CurrentRecordFlag] [tinyint] NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobMSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [PackageExecutionId] [bigint] NOT NULL,
     [JobDeletedFlag] [tinyint] NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobMSSQL_JobDeletedFlag] DEFAULT ((0)),
     [JobIdentifier] [varchar](40) NOT NULL,
     [JobName] [varchar](128) NOT NULL,
     [JobEnabledFlag] [tinyint] NOT NULL,
     [JobDescription] [varchar](1024) NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobMSSQL_JobDescription] DEFAULT (''),
     [OwnerName] [varchar](128) NOT NULL,
     [CategoryId] [int] NOT NULL,
     [CategoryName] [varchar](128) NOT NULL,
     [StartStepId] [int] NOT NULL,
     [NotifyLevelEventlogDesc] [varchar](30) NOT NULL,
     [NotifyLevelEmailDesc] [varchar](30) NOT NULL,
     [NotifyLevelNetsendDesc] [varchar](30) NOT NULL,
     [NotifyLevelPageDesc] [varchar](30) NOT NULL,
     [NotifyEmailOperator] [varchar](128) NOT NULL,
     [NotifyNetsendOperator] [varchar](128) NOT NULL,
     [NotifyPageOperator] [varchar](128) NOT NULL,
     [CrDt] [datetime] NOT NULL,
     [ModDt] [datetime] NOT NULL,
     [VersionNumber] [int] NOT NULL,
     CONSTRAINT [PK_SrvrInstncSchedJobMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [SrvrInstncSchedJobId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncSchedJobScheduleMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncSchedJobScheduleMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncSchedJobScheduleMSSQL](
     [SrvrInstncId]             [int]              NOT NULL,
     [SrvrInstncSchedJobId]     [int]              NOT NULL,
     [ScheduleId]               [int]              NOT NULL,
     [StartDt]                  [datetime]         NOT NULL,
     [EndDt]                    [datetime]         NOT NULL,
     [CurrentRecordFlag]        [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobScheduleMSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [PackageExecutionId]       [bigint]           NOT NULL,
     [ScheduleDeletedFlag]      [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobScheduleMSSQL_ScheduleDeletedFlag] DEFAULT ((0)),
     [ScheduleIdentifier]       [uniqueidentifier]     NULL,
     [ScheduleName]             [varchar](128)     NOT NULL,
     [ScheduleOriginServerName] [varchar](128)     NOT NULL,
     [ScheduleOwnerName]        [varchar](128)     NOT NULL,
     [ScheduleEnabledFlag]      [tinyint]          NOT NULL,
     [ScheduleDescription]      [varchar](255)     NOT NULL,
     [ScheduleCrDt]             [datetime]         NOT NULL,
     [ScheduleLastModDt]        [datetime]             NULL,
     [ScheduleVersion]          [int]                  NULL,
     [CodedRawSchedule]         [varchar](120)     NOT NULL,
     CONSTRAINT [PK_SrvrInstncSchedJobScheduleMSSQL] PRIMARY KEY CLUSTERED 
     ( [SrvrInstncId] ASC, [SrvrInstncSchedJobId] ASC, [ScheduleId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncSchedJobStepMSSQL]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncSchedJobStepMSSQL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncSchedJobStepMSSQL](
     [SrvrInstncId]                   [int]              NOT NULL,
     [SrvrInstncSchedJobId]           [int]              NOT NULL,
     [StepId]                         [int]              NOT NULL,
     [StartDt]                        [datetime]         NOT NULL,
     [EndDt]                          [datetime]         NOT NULL,
     [CurrentRecordFlag]              [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobStepMSSQL_CurrentRecordFlag] DEFAULT ((0)),
     [PackageExecutionId]             [bigint]           NOT NULL,
     [StepDeletedFlag]                [tinyint]          NOT NULL CONSTRAINT [DF_SrvrInstncSchedJobStepMSSQL_StepDeletedFlag] DEFAULT ((0)),
     [StepIdentifier]                 [uniqueidentifier] NOT NULL,
     [StepName]                       [varchar](128)     NOT NULL,
     [SubSystem]                      [varchar](40)      NOT NULL,
     [Command]                        [nvarchar](max)    NOT NULL,
     [IncludeStepOutputInHistoryFlag] [tinyint]          NOT NULL,
     [LogToTableFlag]                 [tinyint]          NOT NULL,
     [LogToTableAppendOutputFlag]     [tinyint]          NOT NULL,
     [AppendOutputToOutputFileFlag]   [tinyint]          NOT NULL,
     [CmdExecSuccessCode]             [int]              NOT NULL,
     [OnSuccessAction]                [varchar](30)      NOT NULL,
     [OnFailAction]                   [varchar](30)      NOT NULL,
     [OnSuccessStepId]                [int]              NOT NULL,
     [OnFailStepId]                   [int]              NOT NULL,
     [ServerName]                     [varchar](128)         NULL,
     [DatabaseName]                   [varchar](128)         NULL,
     [DatabaseUserName]               [varchar](128)         NULL,
     [RetryAttempts]                  [int]              NOT NULL,
     [RetryIntervalInMinutes]         [int]              NOT NULL,
     [OSRunPriority]                  [int]              NOT NULL,
     [OutputFileName]                 [varchar](200)         NULL,
     [ProxyName]                      [varchar](128)         NULL,
     CONSTRAINT [PK_SrvrInstncSchedJobStepMSSQL] PRIMARY KEY CLUSTERED ( [SrvrInstncId] ASC, [SrvrInstncSchedJobId] ASC, [StepId] ASC, [StartDt] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncSSRSExecLog](
     [SrvrInstncDatabaseId] [int] NOT NULL,
     [InstanceName]         [nvarchar](38) NOT NULL,
     [ReportIdentifier]     [nvarchar](425) NULL,
     [UserName]             [nvarchar](260) NULL,
     [ExecutionId]          [nvarchar](64) NULL,
     [RequestType]          [varchar](13) NOT NULL,
     [Format]               [nvarchar](26) NULL,
     [Parameters]           [nvarchar](max) NULL,
     [ReportAction]         [varchar](21) NOT NULL,
     [TimeStart]            [datetime] NOT NULL,
     [TimeEnd]              [datetime] NOT NULL,
     [TimeDataRetrieval]    [int] NOT NULL,
     [TimeProcessing]       [int] NOT NULL,
     [TimeRendering]        [int] NOT NULL,
     [Source]               [varchar](8) NOT NULL,
     [Status]               [nvarchar](40) NOT NULL,
     [ByteCount]            [bigint] NOT NULL,
     [RowCount]             [bigint] NOT NULL,
     [AdditionalInfo]       [xml] NULL
) ON [PRIMARY] TEXTIMAGE_ON [Data_BLOB]

GO

SET ANSI_PADDING OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SrvrInstncType]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[SrvrInstncType]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[SrvrInstncType](
     [SrvrInstncTypeId]   [int]          NOT NULL,
     [SrvrInstncTypeCd]   [varchar](10)  NOT NULL,
     [SrvrInstncTypeName] [varchar](128) NOT NULL,
     [OLEDBProviderName]  [varchar](128) NOT NULL,
     [LastModDt]          [datetime]     NOT NULL CONSTRAINT [DF_SrvrInstncType_LastModDt] DEFAULT (getdate()),
     CONSTRAINT [PK_SrvrInstncType] PRIMARY KEY CLUSTERED ( [SrvrInstncTypeId] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

CREATE NONCLUSTERED INDEX [IX_SrvrInstncType_Code] ON [dbo].[SrvrInstncType] ( [SrvrInstncTypeCd] ASC ) ON [Data_Index]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Unique Identifier of a particular Server Instance Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType', @level2type=N'COLUMN',@level2name=N'SrvrInstncTypeId'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Secondary Unique Identifier of a particular Server Instance Type, user defined.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType', @level2type=N'COLUMN',@level2name=N'SrvrInstncTypeCd'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User-friendly description of the Server Instance Type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType', @level2type=N'COLUMN',@level2name=N'SrvrInstncTypeName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The name of the OLEDB provider, used to build generic connection strings.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType', @level2type=N'COLUMN',@level2name=N'OLEDBProviderName'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The last date/time the record was changed.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType', @level2type=N'COLUMN',@level2name=N'LastModDt'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Server instance types.  Contains master list of server instance types such as MSSQL, SYBASE, and ORACLE.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SrvrInstncType'
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UnresolvedMSSQLInstnc]') AND type in (N'U'))
BEGIN
     DROP TABLE [dbo].[UnresolvedMSSQLInstnc]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[UnresolvedMSSQLInstnc](
     [UnresolvedMSSQLInstncId] [int] IDENTITY(1,1) NOT NULL,
     [PackageExecutionId]      [bigint]            NOT NULL,
     [FullInstanceName]        [varchar](255)      NOT NULL,
     [MachineName]             [varchar](128)      NOT NULL,
     [InstanceName]            [varchar](128)      NOT NULL,
     [LoginName]               [varchar](128)      NOT NULL,
     [ServiceRunningFlag]      [int]               NOT NULL,
     [IsClusteredFlag]         [int]                   NULL,
     [ErrorDesc]               [varchar](255)          NULL,
     CONSTRAINT [PK_UnresolvedMSSQLInstnc] PRIMARY KEY CLUSTERED ( [UnresolvedMSSQLInstncId] ASC, [FullInstanceName] ASC )
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'sysdtslog90' AND schema_id = 1 )
BEGIN
     DROP VIEW [dbo].[sysdtslog90]
END
GO

CREATE VIEW [dbo].[sysdtslog90]
AS
/*
 *
 * sysdtslog90
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/07/2009, 1.00.0000
 *
 */
SELECT [id]          = EventLogId,
       [event]       = MiscVC1,
       [computer]    = MiscVC2,
       [operator]    = MiscVC3,
       [source]      = CONVERT( varchar(1024), TraceText ),
       [sourceid]    = MiscGUID1,
       [executionid] = MiscGUID4,
       [starttime]   = MiscDt1,
       [endtime]     = MiscDt2,
       [datacode]    = MiscInt1,
       [databytes]   = TraceImage,
       [message]     = CONVERT( varchar(2048), LogText )
FROM   dbo.EventLog
WHERE  LogByApp          = 'Integration Services'
AND    LogByAppSubSystem = 'sp_dts_addlogentry'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'sysssislog' AND schema_id = 1 )
BEGIN
     DROP VIEW [dbo].[sysssislog]
END
GO

CREATE VIEW [dbo].[sysssislog]
AS
/*
 *
 * sysssislog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/07/2009, 1.00.0000
 *
 */
SELECT [id]          = EventLogId,
       [event]       = MiscVC1,
       [computer]    = MiscVC2,
       [operator]    = MiscVC3,
       [source]      = CONVERT( varchar(1024), TraceText ),
       [sourceid]    = MiscGUID1,
       [executionid] = MiscGUID4,
       [starttime]   = MiscDt1,
       [endtime]     = MiscDt2,
       [datacode]    = MiscInt1,
       [databytes]   = TraceImage,
       [message]     = CONVERT( varchar(2048), LogText )
FROM   dbo.EventLog
WHERE  LogByApp          = 'Integration Services'
AND    LogByAppSubSystem = 'sp_ssis_addlogentry'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vDDLActivity' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vDDLActivity
END
GO

CREATE VIEW dbo.vDDLActivity

AS
/*
 *
 * vDDLActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/30/2009, 1.00.0000
 *
 */
SELECT DDLActivityId    = EventLogId,
       DDLActivityDt    = LogDt,
       HostName,
       AppName,
       LoginName,
       DatabaseUserName,
       EventType        = MiscVC1,
       DatabaseName,
       SchemaName       = MiscVC2,
       ObjectName       = MiscVC3,
       ObjectType       = MiscVC4,
       SPID,
       TSQLCommand      = TraceText 
FROM   dbo.EventLog 
WHERE  LogByApp          = 'LogAllDDL'
AND    LogByAppSubSystem = 'InsDDLActivity'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vLogonActivity' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vLogonActivity
END
GO

CREATE VIEW dbo.vLogonActivity

AS
/*
 *
 * vLogonActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/30/2009, 1.00.0000
 *
 */
SELECT LoginActivityId  = EventLogId,
       LoginActivityDt  = MiscDt1,
       HostName,
       AppName,
       LoginName,
       LoginSID         = [SID],
       IsPooledFlag     = CONVERT( tinyint, MiscTinyint1 ),
       NetTransport     = MiscVC1,
       NetAddress       = MiscVC2,
       SPID
FROM   dbo.EventLog 
WHERE  LogByApp          = 'LogAllLogon'
AND    LogByAppSubSystem = 'InsLogonActivity'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMasterDDLActivity' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vMasterDDLActivity
END
GO

CREATE VIEW dbo.vMasterDDLActivity
AS
/*
 *
 * vMasterDDLActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName     = d.DatabaseName,
       DDLActivityId        = l.EventLogId,
       DDLActivityDt        = l.LogDt,
       l.HostName,
       l.AppName,
       l.LoginName,
       l.DatabaseUserName,
       EventType            = l.MiscVC1,
       l.DatabaseName,
       SchemaName           = l.MiscVC2,
       ObjectName           = l.MiscVC3,
       ObjectType           = l.MiscVC4,
       l.SPID,
       TSQLCommand          = l.TraceText 
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
WHERE  l.LogByApp          = 'LogAllDDL'
AND    l.LogByAppSubSystem = 'InsDDLActivity'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMasterEventLog' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vMasterEventLog
END
GO

CREATE VIEW dbo.vMasterEventLog
AS
/*
 *
 * vMasterEventLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName = d.DatabaseName,
       l.EventLogId, 
       l.EventLogTypeId, 
       l.LogDt, 
       l.HostName, 
       l.LoginName, 
       l.DatabaseUserName, 
       l.DatabaseName, 
       l.AppName, 
       l.SPID, 
       l.SID, 
       l.LogByApp, 
       l.LogByAppSubSystem, 
       l.LogByDesc, 
       l.LogText, 
       l.TraceText, 
       l.TraceImage, 
       l.MiscVC1, 
       l.MiscVC2, 
       l.MiscVC3, 
       l.MiscVC4, 
       l.MiscInt1, 
       l.MiscInt2, 
       l.MiscInt3, 
       l.MiscInt4, 
       l.MiscTinyint1, 
       l.MiscTinyint2, 
       l.MiscTinyint3, 
       l.MiscTinyint4, 
       l.MiscDt1, 
       l.MiscDt2, 
       l.MiscDt3, 
       l.MiscDt4, 
       l.MiscGUID1, 
       l.MiscGUID2, 
       l.MiscGUID3, 
       l.MiscGUID4
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMasterLogonActivity' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vMasterLogonActivity
END
GO

CREATE VIEW dbo.vMasterLogonActivity
AS
/*
 *
 * vMasterLogonActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName     = d.DatabaseName,
       LoginActivityId      = l.EventLogId,
       LoginActivityDt      = l.LogDt,
       l.HostName,
       l.AppName,
       l.LoginName,
       LoginType            = l.MiscVC1,
       LoginSID             = l.SID,
       IsPooledFlag         = l.MiscTinyint1,
       NetTransport         = MiscVC2,
       NetAddress           = MiscVC3,
       l.SPID
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
WHERE  l.LogByApp          = 'LogAllLogon'
AND    l.LogByAppSubSystem = 'InsLogonActivity'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMasterPackageExecutionLog' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vMasterPackageExecutionLog
END
GO

CREATE VIEW dbo.vMasterPackageExecutionLog
AS
/*
 *
 * vMasterPackageExecutionLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName         = d.DatabaseName,
       PackageExecutionId       = l.MiscBigInt1,
       PackageExecutionDt       = l.LogDt,
       PackageName              = l.LogByDesc,
       PackageGUID              = l.MiscGUID1,
       ExecutionGUID            = l.MiscGUID4,
       PackageMajorVersion      = l.MiscInt1,
       PackageMinorVersion      = l.MiscInt2,
       PackageBuildVersion      = l.MiscInt3,
       MachineName              = l.MiscVC1,
       UserName                 = l.MiscVC2,
       ContainerStartTime       = l.MiscDt1,
       PackageStartTime         = l.MiscDt2,
       PackageEndTime           = l.MiscDt3,
       ParentPackageExecutionId = l.MiscBigInt2,
       PackageStateId           = MiscTinyInt1,
       PackageStateDesc         = CONVERT( varchar(10), CASE WHEN MiscTinyint1 = 1
                                                             THEN 'Start'
                                                             WHEN MiscTinyint1 = 128
                                                             THEN 'Info'
                                                             WHEN MiscTinyint1 = 255
                                                             THEN 'End'
                                                             ELSE 'Unknown'
                                                        END )
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
WHERE  l.LogByApp          = 'Integration Services'
AND    l.LogByAppSubSystem = 'InsPackageExecutionLog'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMastersysdtslog90' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vMastersysdtslog90
END
GO

CREATE VIEW dbo.vMastersysdtslog90
AS
/*
 *
 * vMastersysdtslog90
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName = d.DatabaseName,
       [id]             = EventLogId,
       [event]          = MiscVC1,
       [computer]       = MiscVC2,
       [operator]       = MiscVC3,
       [source]         = CONVERT( varchar(1024), TraceText ),
       [sourceid]       = MiscGUID1,
       [executionid]    = MiscGUID4,
       [starttime]      = MiscDt1,
       [endtime]        = MiscDt2,
       [datacode]       = MiscInt1,
       [databytes]      = TraceImage,
       [message]        = CONVERT( varchar(2048), LogText )
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
WHERE  l.LogByApp          = 'Integration Services'
AND    l.LogByAppSubSystem = 'sp_dts_addlogentry'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vMastersysssislog' AND schema_id = 1 )
BEGIN
     DROP VIEW [dbo].[vMastersysssislog]
END
GO

CREATE VIEW [dbo].[vMastersysssislog]
AS
/*
 *
 * vMastersysssislog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
SELECT i.SrvrInstncFullName,
       i.SrvrInstncId, 
       SrvrDatabaseName = d.DatabaseName,
       [id]             = EventLogId,
       [event]          = MiscVC1,
       [computer]       = MiscVC2,
       [operator]       = MiscVC3,
       [source]         = CONVERT( varchar(1024), TraceText ),
       [sourceid]       = MiscGUID1,
       [executionid]    = MiscGUID4,
       [starttime]      = MiscDt1,
       [endtime]        = MiscDt2,
       [datacode]       = MiscInt1,
       [databytes]      = TraceImage,
       [message]        = CONVERT( varchar(2048), LogText )
FROM   dbo.MasterEventLog l INNER JOIN dbo.SrvrInstncDatabase d
          ON l.SrvrInstncDatabaseId = d.SrvrInstncDatabaseId
       INNER JOIN dbo.SrvrInstnc i
          ON d.SrvrInstncId = i.SrvrInstncId 
WHERE  l.LogByApp          = 'Integration Services'
AND    l.LogByAppSubSystem = 'sp_ssis_addlogentry'
GO
IF EXISTS ( SELECT 'X' FROM sys.views WHERE name = 'vPackageExecutionLog' AND schema_id = 1 )
BEGIN
     DROP VIEW dbo.vPackageExecutionLog
END
GO

CREATE VIEW dbo.vPackageExecutionLog
AS
/*
 *
 * vPackageExecutionLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/30/2009, 1.00.0000
 *
 */
SELECT PackageExecutionId       = MiscBigInt1,
       PackageExecutionDt       = LogDt,
       PackageName              = LogByDesc,
       PackageGUID              = MiscGUID1,
       ExecutionGUID            = MiscGUID4,
       PackageMajorVersion      = MiscInt1,
       PackageMinorVersion      = MiscInt2,
       PackageBuildVersion      = MiscInt3,
       MachineName              = MiscVC1,
       UserName                 = MiscVC2,
       ContainerStartTime       = MiscDt1,
       PackageStartTime         = MiscDt2,
       PackageEndTime           = MiscDt3,
       ParentPackageExecutionId = MiscBigInt2,
       PackageStateId           = MiscTinyInt1,
       PackageStateDesc         = CONVERT( varchar(10), CASE WHEN MiscTinyint1 = 1
                                                             THEN 'Start'
                                                             WHEN MiscTinyint1 = 128
                                                             THEN 'Info'
                                                             WHEN MiscTinyint1 = 255
                                                             THEN 'End'
                                                             ELSE 'Unknown'
                                                        END )
FROM   dbo.EventLog 
WHERE  LogByApp          = 'Integration Services'
AND    LogByAppSubSystem = 'InsPackageExecutionLog'
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_EventLog_EventLogType]') AND parent_object_id = OBJECT_ID(N'[dbo].[EventLog]'))
BEGIN
     ALTER TABLE [dbo].[EventLog] DROP CONSTRAINT [FK_EventLog_EventLogType]
END
GO

ALTER TABLE [dbo].[EventLog] WITH CHECK ADD CONSTRAINT [FK_EventLog_EventLogType] 
     FOREIGN KEY([EventLogTypeId]) REFERENCES [dbo].[EventLogType] ([EventLogTypeId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineCluster_Machine_ClusterMachine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineCluster]'))
BEGIN
     ALTER TABLE [dbo].[MachineCluster] DROP CONSTRAINT [FK_MachineCluster_Machine_ClusterMachine]
END
GO

ALTER TABLE [dbo].[MachineCluster] WITH CHECK ADD CONSTRAINT [FK_MachineCluster_Machine_ClusterMachine] 
     FOREIGN KEY([ClusterMachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineCluster_Machine_MemberMachine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineCluster]'))
BEGIN
     ALTER TABLE [dbo].[MachineCluster] DROP CONSTRAINT [FK_MachineCluster_Machine_MemberMachine]
END
GO

ALTER TABLE [dbo].[MachineCluster] WITH CHECK ADD CONSTRAINT [FK_MachineCluster_Machine_MemberMachine] 
     FOREIGN KEY([MemberMachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineDriveVolumeSpace_Machine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineDriveVolumeSpace]'))
BEGIN
     ALTER TABLE [dbo].[MachineDriveVolumeSpace] DROP CONSTRAINT [FK_MachineDriveVolumeSpace_Machine]
END
GO

ALTER TABLE [dbo].[MachineDriveVolumeSpace] WITH CHECK ADD CONSTRAINT [FK_MachineDriveVolumeSpace_Machine] 
     FOREIGN KEY([MachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineDriveVolume_Machine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineDriveVolume]'))
BEGIN
     ALTER TABLE [dbo].[MachineDriveVolume] DROP CONSTRAINT [FK_MachineDriveVolume_Machine]
END
GO

ALTER TABLE [dbo].[MachineDriveVolume] WITH CHECK ADD CONSTRAINT [FK_MachineDriveVolume_Machine] 
     FOREIGN KEY([MachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineEnvVar_Machine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineEnvVar]'))
BEGIN
     ALTER TABLE [dbo].[MachineEnvVar] DROP CONSTRAINT [FK_MachineEnvVar_Machine]
END
GO

ALTER TABLE [dbo].[MachineEnvVar] WITH CHECK ADD CONSTRAINT [FK_MachineEnvVar_Machine] 
     FOREIGN KEY([MachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineMSInstalledComponents_Machine]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineMSInstalledComponents]'))
BEGIN
     ALTER TABLE [dbo].[MachineMSInstalledComponents] DROP CONSTRAINT [FK_MachineMSInstalledComponents_Machine]
END
GO

ALTER TABLE [dbo].[MachineMSInstalledComponents] WITH CHECK ADD CONSTRAINT [FK_MachineMSInstalledComponents_Machine] 
     FOREIGN KEY([MachineId]) REFERENCES [dbo].[Machine] ([MachineId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineMSInstalledComponents_SrvrInstnc_RelatedToSrvrInstncId]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineMSInstalledComponents]'))
BEGIN
     ALTER TABLE [dbo].[MachineMSInstalledComponents] DROP CONSTRAINT [FK_MachineMSInstalledComponents_SrvrInstnc_RelatedToSrvrInstncId]
END
GO

ALTER TABLE [dbo].[MachineMSInstalledComponents] WITH CHECK ADD CONSTRAINT [FK_MachineMSInstalledComponents_SrvrInstnc_RelatedToSrvrInstncId] 
     FOREIGN KEY([RelatedToSrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MachineMSInstalledComponents_SrvrInstnc_SrvrInstncId]') AND parent_object_id = OBJECT_ID(N'[dbo].[MachineMSInstalledComponents]'))
BEGIN
     ALTER TABLE [dbo].[MachineMSInstalledComponents] DROP CONSTRAINT [FK_MachineMSInstalledComponents_SrvrInstnc_SrvrInstncId]
END
GO

ALTER TABLE [dbo].[MachineMSInstalledComponents] WITH CHECK ADD CONSTRAINT [FK_MachineMSInstalledComponents_SrvrInstnc_SrvrInstncId] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MasterEventLogType_SrvrInstncDatabase]') AND parent_object_id = OBJECT_ID(N'[dbo].[MasterEventLogType]'))
BEGIN
     ALTER TABLE [dbo].[MasterEventLogType] DROP CONSTRAINT [FK_MasterEventLogType_SrvrInstncDatabase]
END
GO

ALTER TABLE [dbo].[MasterEventLogType] WITH CHECK ADD CONSTRAINT [FK_MasterEventLogType_SrvrInstncDatabase] 
     FOREIGN KEY([SrvrInstncDatabaseId]) REFERENCES [dbo].[SrvrInstncDatabase] ([SrvrInstncDatabaseId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_MasterEventLog_MasterEventLogType]') AND parent_object_id = OBJECT_ID(N'[dbo].[MasterEventLog]'))
BEGIN
     ALTER TABLE [dbo].[MasterEventLog] DROP CONSTRAINT [FK_MasterEventLog_MasterEventLogType]
END
GO

ALTER TABLE [dbo].[MasterEventLog] ADD CONSTRAINT [FK_MasterEventLog_MasterEventLogType] FOREIGN KEY([SrvrInstncDatabaseId], [EventLogTypeId])
     REFERENCES [dbo].[MasterEventLogType] ([SrvrInstncDatabaseId], [EventLogTypeId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncAlias_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncAlias]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncAlias] DROP CONSTRAINT [FK_SrvrInstncAlias_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncAlias] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncAlias_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncCfg1MSSQL_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncCfg1MSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncCfg1MSSQL] DROP CONSTRAINT [FK_SrvrInstncCfg1MSSQL_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncCfg1MSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncCfg1MSSQL_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncCfg2MSSQL_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncCfg2MSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncCfg2MSSQL] DROP CONSTRAINT [FK_SrvrInstncCfg2MSSQL_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncCfg2MSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncCfg2MSSQL_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncDatabaseFileMSSQL_SrvrInstncDatabase]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabaseFileMSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncDatabaseFileMSSQL] DROP CONSTRAINT [FK_SrvrInstncDatabaseFileMSSQL_SrvrInstncDatabase]
END
GO

ALTER TABLE [dbo].[SrvrInstncDatabaseFileMSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncDatabaseFileMSSQL_SrvrInstncDatabase] 
     FOREIGN KEY([SrvrInstncDatabaseId]) REFERENCES [dbo].[SrvrInstncDatabase] ([SrvrInstncDatabaseId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncDatabaseMSSQL_SrvrInstncDatabase]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabaseMSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncDatabaseMSSQL] DROP CONSTRAINT [FK_SrvrInstncDatabaseMSSQL_SrvrInstncDatabase]
END
GO

ALTER TABLE [dbo].[SrvrInstncDatabaseMSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncDatabaseMSSQL_SrvrInstncDatabase] 
     FOREIGN KEY([SrvrInstncDatabaseId]) REFERENCES [dbo].[SrvrInstncDatabase] ([SrvrInstncDatabaseId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncDatabase_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncDatabase]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncDatabase] DROP CONSTRAINT [FK_SrvrInstncDatabase_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncDatabase] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncDatabase_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncEAV_Parameter]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncEAV]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncEAV] DROP CONSTRAINT [FK_SrvrInstncEAV_Parameter]
END
GO

ALTER TABLE [dbo].[SrvrInstncEAV] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncEAV_Parameter] 
     FOREIGN KEY([ParameterId]) REFERENCES [dbo].[Parameter] ([ParameterId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncEAV_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncEAV]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncEAV] DROP CONSTRAINT [FK_SrvrInstncEAV_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncEAV]  WITH CHECK ADD  CONSTRAINT [FK_SrvrInstncEAV_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncMachine_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncMachine]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncMachine] DROP CONSTRAINT [FK_SrvrInstncMachine_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncMachine] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncMachine_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncMemoryCfgMSSQL_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncMemoryCfgMSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncMemoryCfgMSSQL] DROP CONSTRAINT [FK_SrvrInstncMemoryCfgMSSQL_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncMemoryCfgMSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncMemoryCfgMSSQL_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncMSSQL_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncMSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncMSSQL] DROP CONSTRAINT [FK_SrvrInstncMSSQL_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncMSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncMSSQL_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstncSchedJobMSSQL_SrvrInstnc]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstncSchedJobMSSQL]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstncSchedJobMSSQL] DROP CONSTRAINT [FK_SrvrInstncSchedJobMSSQL_SrvrInstnc]
END
GO

ALTER TABLE [dbo].[SrvrInstncSchedJobMSSQL] WITH CHECK ADD CONSTRAINT [FK_SrvrInstncSchedJobMSSQL_SrvrInstnc] 
     FOREIGN KEY([SrvrInstncId]) REFERENCES [dbo].[SrvrInstnc] ([SrvrInstncId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstnc_SrvrInstncGrp]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstnc]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstnc] DROP CONSTRAINT [FK_SrvrInstnc_SrvrInstncGrp]
END
GO

ALTER TABLE [dbo].[SrvrInstnc] WITH CHECK ADD CONSTRAINT [FK_SrvrInstnc_SrvrInstncGrp] 
     FOREIGN KEY([SrvrInstncGrpId]) REFERENCES [dbo].[SrvrInstncGrp] ([SrvrInstncGrpId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SrvrInstnc_SrvrInstncType]') AND parent_object_id = OBJECT_ID(N'[dbo].[SrvrInstnc]'))
BEGIN
     ALTER TABLE [dbo].[SrvrInstnc] DROP CONSTRAINT [FK_SrvrInstnc_SrvrInstncType]
END
GO

ALTER TABLE [dbo].[SrvrInstnc]  WITH CHECK ADD  CONSTRAINT [FK_SrvrInstnc_SrvrInstncType] 
     FOREIGN KEY([SrvrInstncTypeId]) REFERENCES [dbo].[SrvrInstncType] ([SrvrInstncTypeId])
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'BreakListToIntByDelimeter' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.BreakListToIntByDelimeter
GO

CREATE FUNCTION dbo.BreakListToIntByDelimeter
     ( @ListToBreak varchar(8000),
       @Delimeter   char(1) )
RETURNS @ReturnValue TABLE ( BrokenList int )
AS
/*
 *
 * BreakListToIntByDelimeter
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/15/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @Len    int,
             @StPos  int,
             @EndPos int,
             @WK     varchar(8000)

     -- Add a delimiter to list so we know we have a place to stop
     SELECT @ListToBreak = @ListToBreak + @Delimeter,
            @Len         = LEN(@ListToBreak) + 1,
            @StPos       = 1

     WHILE ( @StPos < @Len )
     BEGIN
          SELECT @EndPos = CHARINDEX( @Delimeter, @ListToBreak, @StPos )
          SELECT @WK = SUBSTRING( @ListToBreak, @StPos, @EndPos - @StPos )

          IF NOT ( @WK IS NULL or @WK = '' )
          BEGIN 
               INSERT @ReturnValue( BrokenList ) SELECT CONVERT( int, @WK )
          END

          SET @StPOS = @EndPos + 1
     END

     RETURN 
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'BreakListToVarcharByDelimeter' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.BreakListToVarcharByDelimeter
GO

CREATE FUNCTION dbo.BreakListToVarcharByDelimeter
     ( @ListToBreak varchar(8000),
       @Delimeter   char(1) )
RETURNS @ReturnValue TABLE ( BrokenList varchar(8000) )
AS
/*
 *
 * BreakListToVarcharByDelimeter
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      Trimming trailing spaces is assumed.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/15/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @Len    int,
             @StPos  int,
             @EndPos int,
             @WK     varchar(8000)

     -- Add a delimiter to list so we know we have a place to stop
     SELECT @ListToBreak = @ListToBreak + @Delimeter,
            @Len         = LEN(@ListToBreak) + 1,
            @StPos       = 1

     WHILE ( @StPos < @Len )
     BEGIN
          SELECT @EndPos = CHARINDEX( @Delimeter, @ListToBreak, @StPos )
          SELECT @WK = RTRIM( SUBSTRING( @ListToBreak, @StPos, @EndPos - @StPos ) )

          IF NOT ( @WK IS NULL or @WK = '' )
          BEGIN 
               INSERT @ReturnValue( BrokenList ) VALUES ( @WK )
          END

          SET @StPOS = @EndPos + 1
     END

     RETURN 
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GenConnectionString' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GenConnectionString
GO

CREATE FUNCTION dbo.GenConnectionString
     ( @TrustedFlag       tinyint,
       @ServerName        varchar(128),
       @DatabaseName      varchar(128),
       @UserName          varchar(128),
       @Password          varchar(128),
       @OLEDBProviderName varchar(128),
       @SuppressPWFlag    tinyint )
RETURNS varchar(512)
AS
/*
 *
 * GenConnectionString
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/09/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(512)

     SELECT @ReturnValue = 'Data Source='
                         + @ServerName
                         + ';Initial Catalog='
                         + @DatabaseName 
                         + ';Provider='
                         + @OLEDBProviderName
                         + ';Auto Translate=False;'
                         + CASE WHEN @TrustedFlag = 1 
                                THEN 'Integrated Security=SSPI;'
                                ELSE 'User ID='
                                   + @UserName
                                   + CASE WHEN @SuppressPWFlag = 1
                                          THEN ';'
                                          ELSE ';Password='
                                             + @Password
                                             + ';'
                                     END
                           END

     RETURN @ReturnValue
END
GO
IF OBJECT_ID (N'dbo.GetCfgCtrlKeyAsBigInt', N'FN') IS NOT NULL
     DROP FUNCTION dbo.GetCfgCtrlKeyAsBigInt
GO

CREATE FUNCTION dbo.GetCfgCtrlKeyAsBigInt
     ( @CfgCtrlKey varchar(30) )
RETURNS bigint 
AS
/*
 *
 * GetCfgCtrlKeyAsBigInt
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/04/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue bigint,
             @TempValue   varchar(8000)
     
     -- Get the temp value by key
     SELECT @TempValue = CfgCtrlValue
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = @CfgCtrlKey

     -- Test the value for numeric, if it is then try the convert, this COULD
     -- fail if the length is 1 and the value is something along the lines of
     -- +/-/$ and a few others, we are chosing not to test for this at this 
     -- time.
     IF ISNUMERIC( @TempValue ) = 1
     BEGIN
          SELECT @ReturnValue = CONVERT( bigint, @TempValue )
     END 
     -- For non-numeric @ReturnValue is already null which is the plan

     RETURN @ReturnValue
END
GO
IF OBJECT_ID (N'dbo.GetCfgCtrlKeyAsInt', N'FN') IS NOT NULL
     DROP FUNCTION dbo.GetCfgCtrlKeyAsInt
GO

CREATE FUNCTION dbo.GetCfgCtrlKeyAsInt
     ( @CfgCtrlKey varchar(30) )
RETURNS int 
AS
/*
 *
 * GetCfgCtrlKeyAsInt
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/04/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue int,
             @TempValue   varchar(8000)
     
     -- Get the temp value by key
     SELECT @TempValue = CfgCtrlValue
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = @CfgCtrlKey

     -- Test the value for numeric, if it is then try the convert, this COULD
     -- fail if the length is 1 and the value is something along the lines of
     -- +/-/$ and a few others, we are chosing not to test for this at this 
     -- time.
     IF ISNUMERIC( @TempValue ) = 1
     BEGIN
          SELECT @ReturnValue = CONVERT( int, @TempValue )
     END 
     -- For non-numeric @ReturnValue is already null which is the plan

     RETURN @ReturnValue
END
GO
IF OBJECT_ID (N'dbo.GetCfgCtrlKeyAsVarchar30', N'FN') IS NOT NULL
     DROP FUNCTION dbo.GetCfgCtrlKeyAsVarchar30
GO

CREATE FUNCTION dbo.GetCfgCtrlKeyAsVarchar30
     ( @CfgCtrlKey varchar(30) )
RETURNS varchar(30)
AS
/*
 *
 * GetCfgCtrlKeyAsVarchar30
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/04/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(30)

     -- Get the value and force it into 30 characters     
     SELECT @ReturnValue = CONVERT( varchar(30), CfgCtrlValue )
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = @CfgCtrlKey

     RETURN @ReturnValue
END
GO
IF OBJECT_ID (N'dbo.GetCfgCtrlKeyAsVarchar8000', N'FN') IS NOT NULL
     DROP FUNCTION dbo.GetCfgCtrlKeyAsVarchar8000
GO

CREATE FUNCTION dbo.GetCfgCtrlKeyAsVarchar8000
     ( @CfgCtrlKey varchar(30) )
RETURNS varchar(8000)
AS
/*
 *
 * GetCfgCtrlKeyAsVarchar8000
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/15/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(8000)

     SELECT @ReturnValue = CfgCtrlValue
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = @CfgCtrlKey

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetDatabaseFileMSSQLIdForServerDatabase' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetDatabaseFileMSSQLIdForServerDatabase
GO

CREATE FUNCTION dbo.GetDatabaseFileMSSQLIdForServerDatabase
     ( @SrvrInstncDatabaseId     int,
       @DatabaseFileId           int,
       @DatabaseFileGUID         uniqueidentifier,
       @FileIsLogFileFlag        tinyint,
       @LogicalFileName          varchar(128),
       @PhysicalFileNameWithPath varchar(255)
     )
RETURNS int
AS
/*
 *
 * GetDatabaseFileMSSQLIdForServerDatabase
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      When other server types are supported this function must be
 *               updated to handle them.
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/27/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue      int,
             @SrvrInstncTypeId int 

     -- Determine Segment Id
     SELECT @SrvrInstncTypeId = SrvrInstncTypeId 
     FROM   dbo.SrvrInstnc si INNER JOIN dbo.SrvrInstncDatabase sid
               ON si.SrvrInstncId = sid.SrvrInstncId
     WHERE  sid.SrvrInstncDatabaseId = @SrvrInstncDatabaseId

     IF ( @SrvrInstncTypeId = 1 )
     BEGIN -- SQL Server
          IF ( @DatabaseFileGUID IS NOT NULL )
          BEGIN
               -- Start with the easiest method, look at the GUID, this is also
               -- the most reliable method.
               SELECT @ReturnValue = SrvrInstncDatabaseFileMSSQLId
               FROM   dbo.SrvrInstncDatabaseFileMSSQL
               WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId
               AND    DatabaseFileGUID     = @DatabaseFileGUID

               IF ( @ReturnValue IS NOT NULL ) GOTO FINISHED
          END

          -- Ok, try with the database id, logical filename and physical filename with path
          SELECT @ReturnValue = SrvrInstncDatabaseFileMSSQLId
          FROM   dbo.SrvrInstncDatabaseFileMSSQL
          WHERE  SrvrInstncDatabaseId     = @SrvrInstncDatabaseId
          AND    DatabaseFileId           = @DatabaseFileId
          AND    LogicalFileName          = @LogicalFileName
          AND    PhysicalFileNameWithPath = @PhysicalFileNameWithPath

          IF ( @ReturnValue IS NOT NULL ) GOTO FINISHED

          -- Ok, try with the logical filename and physical filename with path
          SELECT @ReturnValue = SrvrInstncDatabaseFileMSSQLId
          FROM   dbo.SrvrInstncDatabaseFileMSSQL
          WHERE  SrvrInstncDatabaseId     = @SrvrInstncDatabaseId
          AND    LogicalFileName          = @LogicalFileName
          AND    PhysicalFileNameWithPath = @PhysicalFileNameWithPath

          IF ( @ReturnValue IS NOT NULL ) GOTO FINISHED

          -- We didn't find one so we create one.
          SELECT @ReturnValue = ISNULL( MAX( SrvrInstncDatabaseFileMSSQLId ), 0 ) + 1
          FROM   dbo.SrvrInstncDatabaseFileMSSQL
          WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId

          GOTO FINISHED
     END

     IF ( @SrvrInstncTypeId = 2 )
     BEGIN -- Oracle
          SELECT @ReturnValue = NULL
          GOTO FINISHED
     END

     IF ( @SrvrInstncTypeId = 3 )
     BEGIN -- Sybase
          SELECT @ReturnValue = NULL
          GOTO FINISHED
     END

     FINISHED:
     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetInstanceNameFromMSSQLFullInstanceName' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetInstanceNameFromMSSQLFullInstanceName
GO

CREATE FUNCTION dbo.GetInstanceNameFromMSSQLFullInstanceName
     ( @FullInstanceName varchar(255) )
RETURNS varchar(128)
AS
/*
 *
 * GetInstanceNameFromMSSQLFullInstanceName
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/19/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(128)

     SET @FullInstanceName = LTRIM( RTRIM( @FullInstanceName ) )

     IF ( CHARINDEX( '\', @FullInstanceName ) > 0 )
     BEGIN -- We have a \ which indicates named instance
          SELECT @ReturnValue = RIGHT( @FullInstanceName, LEN( @FullInstanceName ) - CHARINDEX( '\', @FullInstanceName ) )
     END
     ELSE
     BEGIN -- We do not have a \ indicating default instance
          SELECT @ReturnValue = ''
     END

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetMachineIdForMachineName' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetMachineIdForMachineName
GO

CREATE FUNCTION dbo.GetMachineIdForMachineName
     ( @MachineName varchar(255) )
RETURNS int
AS
/*
 *
 * GetMachineIdForMachineName
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue int

     SELECT @ReturnValue = MachineId
     FROM   dbo.Machine 
     WHERE  MachineName   = @MachineName
     OR     FQMachineName = @MachineName

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetMachineNameForMachineId' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetMachineNameForMachineId
GO

CREATE FUNCTION dbo.GetMachineNameForMachineId
     ( @MachineId int )
RETURNS varchar(255)
AS
/*
 *
 * GetMachineNameForMachineId
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/12/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(255)

     SELECT @ReturnValue = COALESCE( FQMachineName, MachineName )
     FROM   dbo.Machine 
     WHERE  MachineId = @MachineId

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetMachineNameFromMSSQLFullInstanceName' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetMachineNameFromMSSQLFullInstanceName
GO

CREATE FUNCTION dbo.GetMachineNameFromMSSQLFullInstanceName
     ( @FullInstanceName varchar(255) )
RETURNS varchar(128)
AS
/*
 *
 * GetMachineNameFromMSSQLFullInstanceName
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/19/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue varchar(128)

     IF ( CHARINDEX( '\', @FullInstanceName ) > 0 )
     BEGIN -- We have a \ which indicates named instance
          SELECT @ReturnValue = LTRIM( LEFT( @FullInstanceName, CHARINDEX( '\', @FullInstanceName ) - 1 ) )
     END
     ELSE
     BEGIN -- We do not have a \ indicating default instance
          SELECT @ReturnValue = LTRIM( RTRIM( @FullInstanceName ) )
     END

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetMachinesForSrvrInstnc' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetMachinesForSrvrInstnc
GO

CREATE FUNCTION dbo.GetMachinesForSrvrInstnc
     ( @SrvrInstncId int )
RETURNS TABLE
AS
/*
 *
 * GetMachinesForSrvrInstnc
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2011, 1.00.0000
 *
 */
RETURN ( 
     SELECT m.MachineId,
            m.MachineName,
            FQMachineName = ISNULL( m.FQMachineName, CONVERT( varchar(255), m.MachineName ) )
     FROM   dbo.SrvrInstncMachine sim INNER JOIN dbo.Machine m
               ON sim.MachineId = m.MachineId
     WHERE  sim.SrvrInstncId = @SrvrInstncId
)
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetMSSQLJobScheduleDescription' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetMSSQLJobScheduleDescription
GO

CREATE FUNCTION dbo.GetMSSQLJobScheduleDescription
     ( @freq_type              INT , 
       @freq_interval          INT , 
       @freq_subday_type       INT , 
       @freq_subday_interval   INT , 
       @freq_relative_interval INT , 
       @freq_recurrence_factor INT , 
       @active_start_date      INT , 
       @active_end_date        INT, 
       @active_start_time      INT , 
       @active_end_time        INT ) 
RETURNS VARCHAR(255)
AS
/*
 *
 * GetMSSQLJobScheduleDescription
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/11/2011, 1.00.0000
 *
 */
BEGIN 
     DECLARE @schedule_description VARCHAR(255) 
     DECLARE @loop INT 

     IF (@freq_type = 0x1) -- OneTime 
     BEGIN 
          SELECT @schedule_description = 'Once on ' 
                                       + CONVERT(VARCHAR(10), @active_start_date) 
                                       + ' at ' 
                                       + CONVERT(VARCHAR(10), cast((@active_start_time / 10000) as varchar(10)) 
                                       + ':' + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2)) 
          RETURN @schedule_description 
     END 

     IF (@freq_type = 0x4) -- Daily 
     BEGIN 
          SELECT @schedule_description = 'Every day ' 
     END 

     IF (@freq_type = 0x8) -- Weekly 
     BEGIN 
          SELECT @schedule_description = 'Every ' 
                                       + CONVERT(NVARCHAR(11), @freq_recurrence_factor) 
                                       + ' week(s) on ' 

          SELECT @loop = 1 

          WHILE (@loop <= 7) 
          BEGIN 
               IF (@freq_interval & POWER(2, @loop - 1) = POWER(2, @loop - 1)) 
               BEGIN
                    SELECT @schedule_description = @schedule_description 
                                                 + DATENAME(dw, '1996120' + CONVERT(NVARCHAR, @loop)) 
                                                 + ', ' 
               END
               
               SELECT @loop = @loop + 1 
          END 

          IF (RIGHT(@schedule_description, 2) = ', ') 
          BEGIN
               SELECT @schedule_description = SUBSTRING(@schedule_description, 1, (DATALENGTH(@schedule_description) / 2) - 2) + ' ' 
          END
     END 

     IF (@freq_type = 0x10) -- Monthly 
     BEGIN 
          SELECT @schedule_description = 'Every ' 
                                       + CONVERT(VARCHAR(11), @freq_recurrence_factor) 
                                       + ' months(s) on day ' 
                                       + CONVERT(VARCHAR(11), @freq_interval) 
                                       + ' of that month ' 
     END 

     IF (@freq_type = 0x20) -- Monthly Relative 
     BEGIN 
          SELECT @schedule_description = 'Every ' 
                                       + CONVERT(VARCHAR(11), @freq_recurrence_factor) 
                                       + ' months(s) on the ' 

          SELECT @schedule_description = @schedule_description 
                                       + CASE @freq_relative_interval 
                                              WHEN 0x01 THEN 'first ' 
                                              WHEN 0x02 THEN 'second ' 
                                              WHEN 0x04 THEN 'third ' 
                                              WHEN 0x08 THEN 'fourth ' 
                                              WHEN 0x10 THEN 'last ' 
                                         END 
                                       + CASE WHEN (@freq_interval > 00) AND (@freq_interval < 08) 
                                              THEN DATENAME(dw, '1996120' + CONVERT(NVARCHAR, @freq_interval)) 
                                              WHEN (@freq_interval = 08) 
                                              THEN 'day' 
                                              WHEN (@freq_interval = 09) 
                                              THEN 'week day' 
                                              WHEN (@freq_interval = 10) 
                                              THEN 'weekend day' 
                                         END 
                                       + ' of that month ' 
     END 

     IF (@freq_type = 0x40) -- AutoStart 
     BEGIN 
          SELECT @schedule_description = FORMATMESSAGE(14579) 
          RETURN @schedule_description 
     END 

     IF (@freq_type = 0x80) -- OnIdle 
     BEGIN 
          SELECT @schedule_description = 'Starts whenever the CPU is idle.'
          RETURN @schedule_description 
     END 

     -- Subday stuff 
     SELECT @schedule_description = @schedule_description 
                                  + CASE @freq_subday_type 
                                         WHEN 0x1 THEN 'at ' 
                                                     + CONVERT(VARCHAR(10), cast((@active_start_time / 10000) as varchar(10)) 
                                                     + ':' 
                                                     + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2)) 
                                         WHEN 0x2 THEN 'every ' 
                                                     + CONVERT(VARCHAR(11), @freq_subday_interval) 
                                                     + ' second(s)' 
                                         WHEN 0x4 THEN 'every ' 
                                                     + CONVERT(VARCHAR(11), @freq_subday_interval) 
                                                     + ' minute(s)' 
                                         WHEN 0x8 THEN 'every ' 
                                                     + CONVERT(VARCHAR(11), @freq_subday_interval) 
                                                     + ' hour(s)' 
                                    END 

     IF (@freq_subday_type IN (0x2, 0x4, 0x8)) 
     BEGIN
          SELECT @schedule_description = @schedule_description 
                                       + ' between ' 
                                       + CONVERT(NVARCHAR, cast((@active_start_time / 10000) as varchar(10)) + ':' + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2) ) + N' and ' + CONVERT(NVARCHAR, cast((@active_end_time / 10000) as varchar(10)) + ':' + right('00' + cast((@active_end_time % 10000) / 100 as varchar(10)),2) ) 
     END

     RETURN @schedule_description 
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetParameterCdExistsBySrvrInstncId' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetParameterCdExistsBySrvrInstncId
GO

CREATE FUNCTION dbo.GetParameterCdExistsBySrvrInstncId
     ( @SrvrInstncId int,
       @ParameterCd  varchar(30) )
RETURNS tinyint
AS
/*
 *
 * GetParameterCdExistsBySrvrInstncId
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      Database is not affected.
 *
 * Returns:      Effective boolean representing whether the parameter exists.
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/16/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue tinyint

     IF EXISTS ( SELECT 'X'
                 FROM   dbo.SrvrInstncEAV sie INNER JOIN dbo.Parameter p
                           ON sie.ParameterId  = p.ParameterId 
                          AND sie.SrvrInstncId = @SrvrInstncId
                          AND p.ParameterCd    = @ParameterCd )
     BEGIN
          SET @ReturnValue = 1
     END
     ELSE
     BEGIN
          SET @ReturnValue = 0
     END
                         
     RETURN @ReturnValue
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetParameterCdExistsBySrvrInstncIdMultiId' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetParameterCdExistsBySrvrInstncIdMultiId
GO

CREATE FUNCTION dbo.GetParameterCdExistsBySrvrInstncIdMultiId
     ( @SrvrInstncId     int,
       @ParameterMultiId int,
       @ParameterCd      varchar(30) )
RETURNS tinyint
AS
/*
 *
 * GetParameterCdExistsBySrvrInstncIdMultiId
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      Database is not affected.
 *
 * Returns:      Effective boolean representing whether the parameter exists.
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/31/2011, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue tinyint

     IF EXISTS ( SELECT 'X'
                 FROM   dbo.SrvrInstncEAV sie INNER JOIN dbo.Parameter p
                           ON sie.ParameterId      = p.ParameterId 
                          AND sie.SrvrInstncId     = @SrvrInstncId
                          AND sie.ParameterMultiId = @ParameterMultiId
                          AND p.ParameterCd         = @ParameterCd )
     BEGIN
          SET @ReturnValue = 1
     END
     ELSE
     BEGIN
          SET @ReturnValue = 0
     END
                         
     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetParameterIdByParameterCd' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetParameterIdByParameterCd
GO

CREATE FUNCTION dbo.GetParameterIdByParameterCd
     ( @ParameterCd varchar(30) )
RETURNS int
AS
/*
 *
 * GetParameterIdByParameterCd
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/16/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue int

     SELECT @ReturnValue = ParameterId
     FROM   dbo.Parameter
     WHERE  ParameterCd = @ParameterCd
     
     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetRSVDMemoryMBByTotalMemoryMB' AND type IN ('FN','IF','TF'))
     DROP FUNCTION dbo.GetRSVDMemoryMBByTotalMemoryMB
GO

CREATE FUNCTION dbo.GetRSVDMemoryMBByTotalMemoryMB
     ( @TotalMemoryMB int )
RETURNS int
AS
/*
 *
 * GetRSVDMemoryMBByTotalMemoryMB
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/09/2009, 1.00.0000
 *
 */
BEGIN
     DECLARE @ReturnValue int

     IF ( @TotalMemoryMB IS NULL ) 
     BEGIN
          SET @ReturnValue = NULL 
     END
     ELSE
     BEGIN
          DECLARE @Ranges TABLE ( LowMB int NOT NULL, HighMB int NOT NULL, RSVDMB int NOT NULL )

          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (     0,        768,  768 ) -- 0MB-768MB ALL Memory RSVD
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (   769,       2048,  512 ) -- 769MB-2GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (  2049,       3584,  768 ) -- 2GB-3.5GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (  3585,       5120, 1024 ) -- 3.5GB-5GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (  5121,       6656, 1280 ) -- 5GB-6.5GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (  6657,       8192, 1536 ) -- 6.5GB-8GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES (  8193,      10240, 1792 ) -- 8GB-10GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES ( 10241,      65536, 2048 ) -- 10GB-64GB
          INSERT @Ranges ( LowMB, HighMB, RSVDMB ) VALUES ( 65537, 2147483647, 3072 ) -- 64GB-Above

          SELECT @ReturnValue = RSVDMB 
          FROM   @Ranges
          WHERE  @TotalMemoryMB BETWEEN LowMB AND HighMB
     END

     RETURN @ReturnValue
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'trUpdCfgCtrl' AND type = 'TR')
     DROP TRIGGER dbo.trUpdCfgCtrl
GO

CREATE TRIGGER dbo.trUpdCfgCtrl ON dbo.CfgCtrl FOR UPDATE
/*
 *
 * trUpdCfgCtrl
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/11/2009, 1.00.0000
 *
 */
AS
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Handle Last Mod Date Logic
     UPDATE [dbo].[CfgCtrl] 
     SET    [LastModDt] = CURRENT_TIMESTAMP 
     FROM   [dbo].[CfgCtrl] d, 
            inserted i 
     WHERE  i.[CfgCtrlKey] = d.[CfgCtrlKey]

     -- Get changed columns
     DECLARE @CU varbinary(255)
     SET @CU = COLUMNS_UPDATED()

     -- Declare table variable to hold flags indicating that that field changed
     -- in at least one record, we use this to cut the number of fields that the
     -- trigger must actually evaluate to determine whether there was a change.
     DECLARE @TABLE TABLE ( [CfgCtrlKey] tinyint NULL,
                            [CfgCtrlValue] tinyint NULL,
                            [CfgCtrlDescription] tinyint NULL,
                            [LastModDt] tinyint NULL )

     -- Populate the table variable with flags indicating all fields that have 
     -- Changed in any record, this handles the single or multi row update case
     INSERT @TABLE
          ( [CfgCtrlKey],
            [CfgCtrlValue],
            [CfgCtrlDescription],
            [LastModDt] )
     SELECT CASE WHEN SUBSTRING( @CU, 1, 1 ) & POWER(2, 0) > 0 THEN 1 ELSE 0 END,
            CASE WHEN SUBSTRING( @CU, 1, 1 ) & POWER(2, 1) > 0 THEN 1 ELSE 0 END,
            CASE WHEN SUBSTRING( @CU, 1, 1 ) & POWER(2, 2) > 0 THEN 1 ELSE 0 END,
            CASE WHEN SUBSTRING( @CU, 1, 1 ) & POWER(2, 3) > 0 THEN 1 ELSE 0 END

     -- Populate log table, handles changed rows without key changes (normal case)
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [TraceText] )
     SELECT 1, -- Info
            'trUpdCfgCtrl', -- Trigger name
            '', 
            'CfgCtrl', -- Table name
            'Record Modification',
            'Non-Key Change',
            'XML' = ''
                  + '<RecordChange '
                  -- Key Field(s)
                  + 'CfgCtrlKey="'
                  + REPLACE( CONVERT( varchar(8000), i.[CfgCtrlKey] ), '"', '''' )
                  + '" '
                  -- Non-Key Field(s)
                  + CASE WHEN t.[CfgCtrlValue] = 1 
                          AND ( i.[CfgCtrlValue] != d.[CfgCtrlValue]
                             OR ( i.[CfgCtrlValue] IS     NULL AND d.[CfgCtrlValue] IS NOT NULL )
                             OR ( i.[CfgCtrlValue] IS NOT NULL AND d.[CfgCtrlValue] IS     NULL )
                              )
                         THEN 'Pre_CfgCtrlValue="' + ISNULL( REPLACE( CONVERT( varchar(8000), d.[CfgCtrlValue] ), '"', '''' ), '[NULL]' )
                            + '" Post_CfgCtrlValue="' + ISNULL( REPLACE( CONVERT( varchar(8000), i.[CfgCtrlValue] ), '"', '''' ), '[NULL]' )
                            + '" '
                         ELSE ''
                    END
                  + CASE WHEN t.[CfgCtrlDescription] = 1 
                          AND i.[CfgCtrlDescription] != d.[CfgCtrlDescription]
                         THEN 'Pre_CfgCtrlDescription="' + REPLACE( CONVERT( varchar(8000), d.[CfgCtrlDescription] ), '"', '''' )
                            + '" Post_CfgCtrlDescription="' + REPLACE( CONVERT( varchar(8000), i.[CfgCtrlDescription] ), '"', '''' )
                            + '" '
                         ELSE ''
                    END
                  + CASE WHEN t.[LastModDt] = 1 
                          AND i.[LastModDt] != d.[LastModDt]
                         THEN 'Pre_LastModDt="' + REPLACE( CONVERT( varchar(8000), d.[LastModDt] ), '"', '''' )
                            + '" Post_LastModDt="' + REPLACE( CONVERT( varchar(8000), i.[LastModDt] ), '"', '''' )
                            + '" '
                         ELSE ''
                    END
                  + '/>'
     FROM   inserted i, 
            deleted  d,
            @TABLE   t -- Pseudo Cartesian table only has 1 row
     WHERE  i.[CfgCtrlKey] = d.[CfgCtrlKey]

     -- Handle inserted side of key change
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [MiscVC2],
            [TraceText] )
     SELECT 1, -- Info
            'trUpdCfgCtrl', -- Trigger name
            '', 
            'CfgCtrl', -- Table name
            'Record Modification',
            'Key Change',
            'Post Row',
            'XML' = ''
                  + '<RecordChange '
                  + 'CfgCtrlKey="'
                  + REPLACE( CONVERT( varchar(8000), i.[CfgCtrlKey] ), '"', '''' )
                  + '" '
                  + 'CfgCtrlValue="'
                  + ISNULL( REPLACE( CONVERT( varchar(8000), i.[CfgCtrlValue] ), '"', '''' ), '[NULL]' )
                  + '" '
                  + 'CfgCtrlDescription="'
                  + REPLACE( CONVERT( varchar(8000), i.[CfgCtrlDescription] ), '"', '''' )
                  + '" '
                  + 'LastModDt="'
                  + REPLACE( CONVERT( varchar(8000), i.[LastModDt] ), '"', '''' )
                  + '" '
                  + '/>'
     FROM   inserted i
     WHERE  NOT EXISTS ( SELECT 'X'
                         FROM   deleted d
                         WHERE  i.[CfgCtrlKey] = d.[CfgCtrlKey] )

     -- Handle delete side of key change
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [MiscVC2],
            [TraceText] )
     SELECT 1, -- Info
            'trUpdCfgCtrl', -- Trigger name
            '', 
            'CfgCtrl', -- Table name
            'Record Modification',
            'Key Change',
            'Pre Row',
            'XML' = ''
                  + '<RecordChange '
                  + 'CfgCtrlKey="'
                  + REPLACE( CONVERT( varchar(8000), d.[CfgCtrlKey] ), '"', '''' )
                  + '" '
                  + 'CfgCtrlValue="'
                  + ISNULL( REPLACE( CONVERT( varchar(8000), d.[CfgCtrlValue] ), '"', '''' ), '[NULL]' )
                  + '" '
                  + 'CfgCtrlDescription="'
                  + REPLACE( CONVERT( varchar(8000), d.[CfgCtrlDescription] ), '"', '''' )
                  + '" '
                  + 'LastModDt="'
                  + REPLACE( CONVERT( varchar(8000), d.[LastModDt] ), '"', '''' )
                  + '" '
                  + '/>'
     FROM   deleted d
     WHERE  NOT EXISTS ( SELECT 'X'
                         FROM   inserted i
                         WHERE  i.[CfgCtrlKey] = d.[CfgCtrlKey] )
END
GO
IF EXISTS ( SELECT 'X' FROM sys.triggers WHERE name = 'trUpdEventLog' )
BEGIN
     DROP TRIGGER [dbo].[trUpdEventLog]
END
GO

CREATE TRIGGER [dbo].[trUpdEventLog] ON [dbo].[EventLog] 
     FOR UPDATE
AS
/*
 *
 * trUpdEventLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/10/2009, 1.00.0000
 *
 */
BEGIN
     RAISERROR( 'Updates are not allowed to the dbo.EventLog table.', 16, 1 )
     
     ROLLBACK TRANSACTION
END
GO
IF EXISTS ( SELECT 'X' FROM sys.triggers WHERE name = 'trUpdMasterEventLog' )
BEGIN
     DROP TRIGGER dbo.trUpdMasterEventLog
END
GO

CREATE TRIGGER dbo.trUpdMasterEventLog ON dbo.MasterEventLog 
     FOR UPDATE
AS
/*
 *
 * trUpdMasterEventLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/13/2009, 1.00.0000
 *
 */
BEGIN
     RAISERROR( 'Updates are not allowed to the dbo.MasterEventLog table.', 16, 1 )
     
     ROLLBACK TRANSACTION
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GenAGUpdTriggers' AND type = 'P')
     DROP PROCEDURE dbo.GenAGUpdTriggers
GO

CREATE PROCEDURE dbo.GenAGUpdTriggers
     @ExcludeTableList varchar(8000) = NULL,
     @DropNoCreateFlag tinyint       = 0,
     @DropAllAGFlag    tinyint       = 0
AS
/*
 *
 * GenAGUpdTriggers
 *
 * Purpose:      To generate triggers used to capture data changes to tables
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      Triggers are dropped, and/or recreated
 *
 * Returns:      
 *
 * Note(s):      This procedure tries as hard as possible to not deal with any
 *               data in a row-by-row methodology or as Jeff Moden calls it RBAR.
 *               We do three loops, in the first two loops we work our way through
 *               each column ordinal id, and build up the commands one column at
 *               a time, I attempted other methods but found this one to work the
 *               best.  Those loops are basically key fields work, and then 
 *               everything else.  The last loop actually execute the fully built
 *               code against the DB.  I could have generated one ginormous SQL
 *               command but had I done that then if there was a problem with one
 *               view then they would fail from then on.  I would rather have all
 *               the others compile and just deal with the one that didn't.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/02/2009, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Declare local variables
     DECLARE @NOW                    datetime,
             @AlwaysExcludeTableList varchar(8000)

     -- Set initial working values.
     SELECT @NOW                    = GETDATE(),
            @AlwaysExcludeTableList = dbo.GetCfgCtrlKeyAsVarchar8000('GenAGUpdTriggers_AlwaysExclude')

     -- Handle drop all action
     IF ( @DropAllAGFlag = 1 )
     BEGIN
          DECLARE @DropAllCode nvarchar(max)

          SELECT @DropAllCode = ''

          SELECT @DropAllCode = @DropAllCode
                              + 'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''['
                              + s.name
                              + '].['
                              + o.name
                              + ']'', N''TR'')'
                              + ' ) DROP TRIGGER ['
                              + s.name
                              + '].['
                              + o.name
                              + '];'
                              + CHAR(13)+ CHAR(10)
          FROM   sys.extended_properties ep INNER JOIN sys.objects o 
                    ON ep.major_id = o.object_id 
                 INNER JOIN sys.schemas s
                    ON o.schema_id = s.schema_id 
          WHERE  ep.name = 'GenAGUpdTriggers'

          PRINT 'Dropping all auto-generated triggers'          
          EXEC ( @DropAllCode )
          
          RETURN     
     END

     -- Get Table List
     DECLARE @Table TABLE ( TABLE_CATALOG    varchar(128) NOT NULL,
                            TABLE_SCHEMA     varchar(128) NOT NULL,
                            TABLE_NAME       varchar(128) NOT NULL )

     INSERT @Table 
          ( TABLE_CATALOG,
            TABLE_SCHEMA,
            TABLE_NAME )
     SELECT DISTINCT
            t.TABLE_CATALOG,
            t.TABLE_SCHEMA,
            t.TABLE_NAME
     FROM   INFORMATION_SCHEMA.TABLES t
     WHERE  t.TABLE_TYPE = 'BASE TABLE'
     AND    t.TABLE_NAME NOT IN ( 'sysdiagrams' )
     -- We handle the exclusions here, since we do none of the later processes
     -- will try to build for these tables.  We do this twice, once for always
     -- excluded tables and another time for ones that were specified for this
     -- run.  It is better overall to write them to the CfgCtrl table so that
     -- they are always excluded, but if you just need to exclude an extra one
     -- then specifying it is fine.
     AND    NOT EXISTS ( SELECT 'X'
                         FROM   dbo.BreakListToVarcharByDelimeter( @AlwaysExcludeTableList, ',' ) e1
                         WHERE  e1.BrokenList = t.TABLE_NAME )
     AND    NOT EXISTS ( SELECT 'X'
                         FROM   dbo.BreakListToVarcharByDelimeter( @ExcludeTableList, ',' ) e2
                         WHERE  e2.BrokenList = t.TABLE_NAME )

     -- Get Keys
     DECLARE @Key TABLE ( CONSTRAINT_CATALOG varchar(128) NOT NULL,
                          CONSTRAINT_SCHEMA  varchar(128) NOT NULL,
                          TABLE_NAME         varchar(128) NOT NULL,
                          COLUMN_NAME        varchar(128) NOT NULL,
                          ORDINAL_POSITION   int          NOT NULL )

     INSERT @Key 
          ( CONSTRAINT_CATALOG,
            CONSTRAINT_SCHEMA,
            TABLE_NAME,
            COLUMN_NAME,
            ORDINAL_POSITION )
     SELECT kcu.CONSTRAINT_CATALOG,
            kcu.CONSTRAINT_SCHEMA,
            kcu.TABLE_NAME,
            kcu.COLUMN_NAME,
            kcu.ORDINAL_POSITION
     FROM   INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu INNER JOIN @Table t
               ON kcu.TABLE_CATALOG = t.TABLE_CATALOG 
              AND kcu.TABLE_SCHEMA  = t.TABLE_SCHEMA 
              AND kcu.TABLE_NAME    = t.TABLE_NAME 
     WHERE  NOT EXISTS ( SELECT 'X' -- Exclude DRI
                         FROM   INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
                         WHERE  rc.CONSTRAINT_CATALOG = kcu.CONSTRAINT_CATALOG 
                         AND    rc.CONSTRAINT_SCHEMA  = kcu.CONSTRAINT_SCHEMA 
                         AND    rc.CONSTRAINT_NAME    = kcu.CONSTRAINT_NAME )
     AND    kcu.TABLE_NAME NOT IN ( 'sysdiagrams' )
     ORDER BY CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, TABLE_NAME, ORDINAL_POSITION

     -- Get column list for tables
     DECLARE @Column TABLE ( TABLE_CATALOG    varchar(128) NOT NULL,
                             TABLE_SCHEMA     varchar(128) NOT NULL,
                             TABLE_NAME       varchar(128) NOT NULL,
                             COLUMN_NAME      varchar(128) NOT NULL,
                             ORDINAL_POSITION int          NOT NULL,
                             IS_NULLABLE      varchar(10)  NOT NULL,
                             IsKeyFieldFlag   tinyint      NOT NULL DEFAULT 0,
                             LastColumnFlag   tinyint      NOT NULL DEFAULT 0 )

     INSERT @Column 
          ( TABLE_CATALOG,
            TABLE_SCHEMA,
            TABLE_NAME,
            COLUMN_NAME,
            ORDINAL_POSITION,
            IS_NULLABLE )
     SELECT c.TABLE_CATALOG,
            c.TABLE_SCHEMA,
            c.TABLE_NAME,
            c.COLUMN_NAME,
            c.ORDINAL_POSITION,
            c.IS_NULLABLE
     FROM   INFORMATION_SCHEMA.COLUMNS c INNER JOIN @Table t
               ON c.TABLE_CATALOG = t.TABLE_CATALOG 
              AND c.TABLE_SCHEMA  = t.TABLE_SCHEMA 
              AND c.TABLE_NAME    = t.TABLE_NAME 
     ORDER BY c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION

     -- Figure out key columns, if it exists in keys it is a key column..
     UPDATE @Column 
     SET    IsKeyFieldFlag = 1
     FROM   @Column c INNER JOIN @Key k
               ON c.TABLE_CATALOG = k.CONSTRAINT_CATALOG 
              AND c.TABLE_SCHEMA  = k.CONSTRAINT_SCHEMA 
              AND c.TABLE_NAME    = k.TABLE_NAME 
              AND c.COLUMN_NAME   = k.COLUMN_NAME 

     -- Figure out last column
     UPDATE @Column
     SET    LastColumnFlag = 1
     FROM   @Column c,
            ( SELECT TABLE_CATALOG, 
                     TABLE_SCHEMA, 
                     TABLE_NAME, 
                     MAXORDINAL = MAX(ORDINAL_POSITION ) 
              FROM   @Column
              GROUP BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME ) AS cm
     WHERE  c.TABLE_CATALOG    = cm.TABLE_CATALOG 
     AND    c.TABLE_SCHEMA     = cm.TABLE_SCHEMA 
     AND    c.TABLE_NAME       = cm.TABLE_NAME 
     AND    c.ORDINAL_POSITION = cm.MAXORDINAL 

     -- Start building trigger artifacts
     DECLARE @TB TABLE ( RecId              int IDENTITY(1,1) NOT NULL,
                         TABLE_CATALOG      varchar(128)      NOT NULL,
                         TABLE_SCHEMA       varchar(128)      NOT NULL,
                         TABLE_NAME         varchar(128)      NOT NULL,
                         TriggerName        varchar(128)      NOT NULL,
                         AllColumnKeyFlag   tinyint           NOT NULL DEFAULT 0,
                         KeyFieldWHERE      varchar(max)      NOT NULL DEFAULT '',
                         TblDeclareStmt     varchar(max)      NOT NULL DEFAULT '',
                         InsTblStmt         varchar(max)      NOT NULL DEFAULT '',
                         InsTblSelectStmt   varchar(max)      NOT NULL DEFAULT '',
                         XMLKeyFieldStmt    varchar(max)      NOT NULL DEFAULT '',
                         XMLNonKeyFieldStmt varchar(max)      NOT NULL DEFAULT '',
                         DiffCode           varchar(max)      NOT NULL DEFAULT '',
                         KeyChgInsCode      varchar(max)      NOT NULL DEFAULT '',
                         KeyChgDelCode      varchar(max)      NOT NULL DEFAULT '',
                         LMDBaseStmt        varchar(max)          NULL,
                         LMDFullStmt        varchar(max)          NULL,
                         DropTriggerCode    varchar(max)          NULL,
                         FullTriggerCode    varchar(max)          NULL,
                         ExtendedPropCode   varchar(max)          NULL )

     INSERT @TB
          ( TABLE_CATALOG,
            TABLE_SCHEMA,
            TABLE_NAME,
            TriggerName )
     SELECT TABLE_CATALOG,
            TABLE_SCHEMA,
            TABLE_NAME,
            TriggerName = 'trUpd'
                        + TABLE_NAME
                        + '_AG'
     FROM   @Table 

     -- Determine if all fields are key, if they are we won't generate the field diff
     -- logic later.
     UPDATE @TB 
     SET    AllColumnKeyFlag = 1
     FROM   @TB t
     WHERE  NOT EXISTS ( SELECT 'X'
                         FROM   @Column c
                         WHERE  c.TABLE_CATALOG  = t.TABLE_CATALOG 
                         AND    c.TABLE_SCHEMA   = t.TABLE_SCHEMA 
                         AND    c.TABLE_NAME     = t.TABLE_NAME
                         AND    c.IsKeyFieldFlag = 0 )

     -- Build LMD Base Statement where applicable.
     UPDATE @TB
     SET    LMDBaseStmt = '     UPDATE ['
                        + t.TABLE_SCHEMA
                        + '].['
                        + t.TABLE_NAME 
                        + '] '
                        + CHAR(13) + CHAR(10)
                        + '     SET    [LastModDt] = CURRENT_TIMESTAMP '
                        + CHAR(13) + CHAR(10)
                        + '     FROM   [' 
                        + t.TABLE_SCHEMA
                        + '].['
                        + t.TABLE_NAME 
                        + '] d, '
                        + CHAR(13) + CHAR(10)
                        + '            inserted i '
                        + CHAR(13) + CHAR(10)
                        + '     WHERE  '
     FROM   @TB t
     WHERE  EXISTS ( SELECT 'X'
                     FROM   @Column c
                     WHERE  t.TABLE_CATALOG = c.TABLE_CATALOG 
                     AND    t.TABLE_SCHEMA  = c.TABLE_SCHEMA 
                     AND    t.TABLE_NAME    = c.TABLE_NAME 
                     AND    c.COLUMN_NAME   = 'LastModDt' )

     -- Build out key where section
     DECLARE @MaxOrdinal int,
             @WkOrdinal  int

     SELECT @MaxOrdinal = MAX(ORDINAL_POSITION) FROM @Key 
     SET @WkOrdinal = 1

     -- Sorry Jeff..
     WHILE ( @WkOrdinal <= @MaxOrdinal )
     BEGIN
          UPDATE @TB
          SET    KeyFieldWHERE   = KeyFieldWHERE
                                 + CASE WHEN @WkOrdinal = 1
                                        THEN 'i.['
                                        ELSE CHAR(13) + CHAR(10)
                                           + '     AND    i.['
                                   END
                                 + k.COLUMN_NAME 
                                 + '] = d.['
                                 + k.COLUMN_NAME 
                                 + ']',
                 XMLKeyFieldStmt = XMLKeyFieldStmt
                                 + '                  + '''
                                 + k.COLUMN_NAME 
                                 + '="'''
                                 + CHAR(13) + CHAR(10)
                                 + '                  + REPLACE( CONVERT( varchar(8000), i.['
                                 + k.COLUMN_NAME 
                                 + '] ), ''"'', '''''''' )'
                                 + CHAR(13) + CHAR(10)
                                 + '                  + ''" '''
                                 + CHAR(13) + CHAR(10)
          FROM   @TB t INNER JOIN @Key k 
                    ON t.TABLE_CATALOG = k.CONSTRAINT_CATALOG 
                   AND t.TABLE_SCHEMA  = k.CONSTRAINT_SCHEMA 
                   AND t.TABLE_NAME    = k.TABLE_NAME 
          WHERE  k.ORDINAL_POSITION = @WkOrdinal 

          SELECT @WkOrdinal = @WkOrdinal + 1
     END

     -- Build out full field sections
     SELECT @MaxOrdinal = MAX(ORDINAL_POSITION) FROM @Column 
     SET @WkOrdinal = 1

     -- Sorry Jeff..
     WHILE ( @WkOrdinal <= @MaxOrdinal )
     BEGIN
          UPDATE @TB
          SET    TblDeclareStmt     = TblDeclareStmt
                                    + CASE WHEN @WkOrdinal = 1
                                           THEN '     DECLARE @TABLE TABLE ( ['
                                           ELSE '                            ['
                                      END
                                    + c.COLUMN_NAME 
                                    + '] tinyint NULL'
                                    + CASE WHEN c.LastColumnFlag = 1
                                           THEN ' )'
                                           ELSE ','
                                      END
                                    + CHAR(13) + CHAR(10),
                 InsTblStmt         = InsTblStmt
                                    + CASE WHEN @WkOrdinal = 1
                                           THEN '     INSERT @TABLE'
                                              + CHAR(13) + CHAR(10)
                                              + '          ( ['
                                           ELSE '            ['
                                      END
                                    + c.COLUMN_NAME 
                                    + CASE WHEN c.LastColumnFlag = 1
                                           THEN '] )'
                                           ELSE '],'
                                      END
                                    + CHAR(13) + CHAR(10),
                 InsTblSelectStmt   = InsTblSelectStmt
                                    + CASE WHEN @WkOrdinal = 1
                                           THEN '     SELECT CASE WHEN SUBSTRING( @CU, '
                                           ELSE '            CASE WHEN SUBSTRING( @CU, '
                                      END
                                    + CONVERT( varchar(3), ( ( c.ORDINAL_POSITION - 1 ) / 8 ) + 1 )
                                    + ', 1 ) & POWER(2, '
                                    + CONVERT( varchar(3), c.ORDINAL_POSITION - ( ( ( c.ORDINAL_POSITION - 1 ) / 8 ) * 8 ) - 1 )
                                    + ') > 0 THEN 1 ELSE 0 END'
                                    + CASE WHEN c.LastColumnFlag = 1
                                           THEN ''
                                           ELSE ','
                                      END
                                    + CHAR(13) + CHAR(10),
                 XMLNonKeyFieldStmt = XMLNonKeyFieldStmt
                                    + CASE WHEN c.IsKeyFieldFlag = 0
                                           THEN '                  + CASE WHEN t.['
                                              + c.COLUMN_NAME 
                                              + '] = 1 '
                                              + CHAR(13) + CHAR(10)
                                              + CASE WHEN c.IS_NULLABLE = 'NO'
                                                     THEN '                          AND i.['
                                                        + c.COLUMN_NAME 
                                                        + '] != d.['
                                                        + c.COLUMN_NAME 
                                                        + ']'
                                                        + CHAR(13) + CHAR(10)
                                                     ELSE '                          AND ( i.['
                                                        + c.COLUMN_NAME 
                                                        + '] != d.['
                                                        + c.COLUMN_NAME 
                                                        + ']'
                                                        + CHAR(13) + CHAR(10)
                                                        + '                             OR ( i.['
                                                        + c.COLUMN_NAME 
                                                        + '] IS     NULL AND d.['
                                                        + c.COLUMN_NAME 
                                                        + '] IS NOT NULL )'
                                                        + CHAR(13) + CHAR(10)
                                                        + '                             OR ( i.['
                                                        + c.COLUMN_NAME 
                                                        + '] IS NOT NULL AND d.['
                                                        + c.COLUMN_NAME 
                                                        + '] IS     NULL )'
                                                        + CHAR(13) + CHAR(10)
                                                        + '                              )'
                                                        + CHAR(13) + CHAR(10)
                                                END
                                              + '                         THEN ''Pre_'
                                              + c.COLUMN_NAME 
                                              + '="'' + '
                                              + CASE WHEN c.IS_NULLABLE = 'NO'
                                                     THEN ''
                                                     ELSE 'ISNULL( '
                                                END
                                              + 'REPLACE( CONVERT( varchar(8000), d.['
                                              + c.COLUMN_NAME 
                                              + '] ), ''"'', '''''''' )'
                                              + CASE WHEN c.IS_NULLABLE = 'NO'
                                                     THEN ''
                                                     ELSE ', ''[NULL]'' )'
                                                END
                                              + CHAR(13) + CHAR(10)
                                              + '                            + ''" Post_'
                                              + c.COLUMN_NAME 
                                              + '="'' + '
                                              + CASE WHEN c.IS_NULLABLE = 'NO'
                                                     THEN ''
                                                     ELSE 'ISNULL( '
                                                END
                                              + 'REPLACE( CONVERT( varchar(8000), i.['
                                              + c.COLUMN_NAME 
                                              + '] ), ''"'', '''''''' )'
                                              + CASE WHEN c.IS_NULLABLE = 'NO'
                                                     THEN ''
                                                     ELSE ', ''[NULL]'' )'
                                                END
                                              + CHAR(13) + CHAR(10)
                                              + '                            + ''" '''
                                              + CHAR(13) + CHAR(10)
                                              + '                         ELSE '''''
                                              + CHAR(13) + CHAR(10)
                                              + '                    END'
                                              + CHAR(13) + CHAR(10)
                                           ELSE ''
                                      END,
                 KeyChgInsCode      = KeyChgInsCode
                                    + '                  + '''
                                    + c.COLUMN_NAME 
                                    + '="'''
                                    + CHAR(13) + CHAR(10)
                                    + '                  + '
                                    + CASE WHEN c.IS_NULLABLE = 'NO'
                                           THEN ''
                                           ELSE 'ISNULL( '
                                      END
                                    + 'REPLACE( CONVERT( varchar(8000), i.['
                                    + c.COLUMN_NAME 
                                    + '] ), ''"'', '''''''' )'
                                    + CASE WHEN c.IS_NULLABLE = 'NO'
                                           THEN ''
                                           ELSE ', ''[NULL]'' )'
                                      END
                                    + CHAR(13) + CHAR(10)
                                    + '                  + ''" '''
                                    + CHAR(13) + CHAR(10),
                 KeyChgDelCode      = KeyChgDelCode
                                    + '                  + '''
                                    + c.COLUMN_NAME 
                                    + '="'''
                                    + CHAR(13) + CHAR(10)
                                    + '                  + '
                                    + CASE WHEN c.IS_NULLABLE = 'NO'
                                           THEN ''
                                           ELSE 'ISNULL( '
                                      END
                                    + 'REPLACE( CONVERT( varchar(8000), d.['
                                    + c.COLUMN_NAME 
                                    + '] ), ''"'', '''''''' )'
                                    + CASE WHEN c.IS_NULLABLE = 'NO'
                                           THEN ''
                                           ELSE ', ''[NULL]'' )'
                                      END
                                    + CHAR(13) + CHAR(10)
                                    + '                  + ''" '''
                                    + CHAR(13) + CHAR(10)
          FROM   @TB t INNER JOIN @Column c 
                    ON t.TABLE_CATALOG = c.TABLE_CATALOG 
                   AND t.TABLE_SCHEMA  = c.TABLE_SCHEMA 
                   AND t.TABLE_NAME    = c.TABLE_NAME 
          WHERE  c.ORDINAL_POSITION = @WkOrdinal 

          SELECT @WkOrdinal = @WkOrdinal + 1
     END

     -- Build out LMD Full Statement
     UPDATE @TB 
     SET    LMDFullStmt = LMDBaseStmt + KeyFieldWHERE 
     WHERE  LMDBaseStmt IS NOT NULL

     -- Build out DiffCode, handle all columns key case
     UPDATE @TB 
     SET    DiffCode      = CASE WHEN AllColumnKeyFlag = 1
                                 THEN ''
                                 ELSE '
     -- Populate log table, handles changed rows without key changes (normal case)
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [TraceText] )
     SELECT 1, -- Info
            '''
+ TriggerName 
+ ''', -- Trigger name
            '''', 
            '''
+ TABLE_NAME
+ ''', -- Table name
            ''Record Modification'',
            ''Non-Key Change'',
            ''XML'' = ''''
                  + ''<RecordChange ''
                  -- Key Field(s)
'
+ XMLKeyFieldStmt 
+'                  -- Non-Key Field(s)
'
+ XMLNonKeyFieldStmt 
+ '                  + ''/>''
     FROM   inserted i, 
            deleted  d,
            @TABLE   t -- Pseudo Cartesian table only has 1 row
     WHERE  '
+ KeyFieldWHERE 
                       END,
            KeyChgInsCode = '

     -- Handle inserted side of key change
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [MiscVC2],
            [TraceText] )
     SELECT 1, -- Info
            '''
+ TriggerName 
+ ''', -- Trigger name
            '''', 
            '''
+ TABLE_NAME
+ ''', -- Table name
            ''Record Modification'',
            ''Key Change'',
            ''Post Row'',
            ''XML'' = ''''
                  + ''<RecordChange ''
'
+ KeyChgInsCode
+ '                  + ''/>''
     FROM   inserted i
     WHERE  NOT EXISTS ( SELECT ''X''
                         FROM   deleted d
                         WHERE  '
+ REPLACE(KeyFieldWHERE, '     ', '                         ' )
+' )',
            KeyChgDelCode = '

     -- Handle delete side of key change
     INSERT [dbo].[EventLog]
          ( [EventLogTypeId],
            [LogByApp],
            [LogByAppSubSystem],
            [LogByDesc],
            [LogText],
            [MiscVC1],
            [MiscVC2],
            [TraceText] )
     SELECT 1, -- Info
            '''
+ TriggerName 
+ ''', -- Trigger name
            '''', 
            '''
+ TABLE_NAME
+ ''', -- Table name
            ''Record Modification'',
            ''Key Change'',
            ''Pre Row'',
            ''XML'' = ''''
                  + ''<RecordChange ''
'
+ KeyChgDelCode
+ '                  + ''/>''
     FROM   deleted d
     WHERE  NOT EXISTS ( SELECT ''X''
                         FROM   inserted i
                         WHERE  '
+ REPLACE(KeyFieldWHERE, '     ', '                         ' )
+' )'

     -- Build out full trigger
     UPDATE @TB
     SET    DropTriggerCode = 'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''['
                            + TABLE_SCHEMA
                            + '].['
                            + TriggerName 
                            + ']'', N''TR'') ) DROP TRIGGER ['
                            + TABLE_SCHEMA
                            + '].['
                            + TriggerName 
                            + '];',
            FullTriggerCode = '

CREATE TRIGGER ['
+ TriggerName 
+ '] ON ['
+ TABLE_SCHEMA
+ '].['
+ TABLE_NAME
+ '] FOR UPDATE
-- -----------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- 
-- System generated trigger for changed data tracking.  To regenerate please run
-- GenAGUpdTriggers stored procedure
-- 
-- -----------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
AS
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON
'
+ CASE WHEN LMDFullStmt IS NOT NULL 
       THEN CHAR(13) + CHAR(10)
          + '     -- Handle Last Mod Date Logic'
          + CHAR(13) + CHAR(10)
          + LMDFullStmt 
          + CHAR(13) + CHAR(10)
       ELSE ''
  END
+ '
     -- Get changed columns
     DECLARE @CU varbinary(255)
     SET @CU = COLUMNS_UPDATED()

     -- Declare table variable to hold flags indicating that that field changed
     -- in at least one record, we use this to cut the number of fields that the
     -- trigger must actually evaluate to determine whether there was a change.
'
+ TblDeclareStmt 
+ '
     -- Populate the table variable with flags indicating all fields that have 
     -- Changed in any record, this handles the single or multi row update case
'
+ InsTblStmt 
+ InsTblSelectStmt 
+ DiffCode 
+ KeyChgInsCode 
+ KeyChgDelCode 
+ '
END
'
     FROM   @TB

     -- Extended Property Code
     UPDATE @TB 
     SET    ExtendedPropCode = 'EXEC sys.sp_addextendedproperty '
                             + '@name = N''GenAGUpdTriggers'', @value = N'''
                             + CONVERT( varchar(10), @NOW, 101 ) 
                             + ' '
                             + CONVERT( varchar(8), @NOW, 108 )
                             + ''', '
                             + '@level0type = N''SCHEMA'', @level0name = ['
                             + TABLE_SCHEMA 
                             + '], @level1type = N''TABLE'', @level1name = ['
                             + TABLE_NAME 
                             + '], @level2type = N''TRIGGER'', @level2name = ['
                             + TriggerName 
                             + '] '
     FROM   @TB

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- We have the full trigger text built so no we are going to execute the 
     -- text against the database.
     --      
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     DECLARE @stmt   nvarchar(max),
             @msg    varchar(255),
             @retval int
     
     SELECT @MaxOrdinal = MAX(RecId) FROM @TB
     SET @WkOrdinal = 1

     WHILE ( @WkOrdinal <= @MaxOrdinal )
     BEGIN
          SELECT @stmt = DropTriggerCode 
          FROM   @TB 
          WHERE  RecId = @WkOrdinal 

          EXEC @retval = sp_executesql @stmt = @stmt
          
          IF ( @retval = 0 )
          BEGIN
               SELECT @msg = 'Drop Trigger: ['
                           + TriggerName 
                           + '] for Table: ['
                           + TABLE_SCHEMA 
                           + '].['
                           + TABLE_NAME 
                           + '] Successful.'
               FROM   @TB 
               WHERE  RecId = @WkOrdinal 

               PRINT @msg
          END
          ELSE
          BEGIN
               SELECT @msg = 'Drop Trigger: ['
                           + TriggerName 
                           + '] for Table: ['
                           + TABLE_SCHEMA 
                           + '].['
                           + TABLE_NAME 
                           + '] Was NOT Successful.'
               FROM   @TB 
               WHERE  RecId = @WkOrdinal 

               PRINT @msg
          END

          IF ( @DropNoCreateFlag = 0 )
          BEGIN
               -- Create Trigger
               SELECT @stmt = FullTriggerCode 
               FROM   @TB 
               WHERE  RecId = @WkOrdinal 

               EXEC @retval = sp_executesql @stmt = @stmt

               IF ( @retval = 0 )
               BEGIN
                    SELECT @msg = 'Trigger: ['
                                + TriggerName 
                                + '] for Table: ['
                                + TABLE_SCHEMA 
                                + '].['
                                + TABLE_NAME 
                                + '] Created Successfully.'
                    FROM   @TB 
                    WHERE  RecId = @WkOrdinal 

                    PRINT @msg
               END
               ELSE
               BEGIN
                    SELECT @msg = 'Trigger: ['
                                + TriggerName 
                                + '] for Table: ['
                                + TABLE_SCHEMA 
                                + '].['
                                + TABLE_NAME 
                                + '] Was NOT Created Successfully.'
                    FROM   @TB 
                    WHERE  RecId = @WkOrdinal 

                    PRINT @msg
               END

               -- Create extended property.
               SELECT @stmt = ExtendedPropCode 
               FROM   @TB 
               WHERE  RecId = @WkOrdinal 

               EXEC @retval = sp_executesql @stmt = @stmt

               IF ( @retval = 0 )
               BEGIN
                    SELECT @msg = 'Extended Property For Trigger: ['
                                + TriggerName 
                                + '] for Table: ['
                                + TABLE_SCHEMA 
                                + '].['
                                + TABLE_NAME 
                                + '] Created Successfully.'
                    FROM   @TB 
                    WHERE  RecId = @WkOrdinal 

                    PRINT @msg
               END
               ELSE
               BEGIN
                    SELECT @msg = 'Extended Property For Trigger: ['
                                + TriggerName 
                                + '] for Table: ['
                                + TABLE_SCHEMA 
                                + '].['
                                + TABLE_NAME 
                                + '] Was NOT Created Successfully.'
                    FROM   @TB 
                    WHERE  RecId = @WkOrdinal 

                    PRINT @msg
               END
          END
          
          SELECT @WkOrdinal = @WkOrdinal + 1
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'This stored procedure creates data change logging triggers for all tables except the ones that were excluded.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = GenAGUpdTriggers;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GenMSSQLMemory' AND type = 'P')
     DROP PROCEDURE dbo.GenMSSQLMemory
GO

CREATE PROCEDURE dbo.GenMSSQLMemory
     @PackageExecutionId tinyint,
     @DebugFlag          tinyint = 0
AS
/*
 *
 * GenMSSQLMemory
 *
 * Purpose:      To determine the memory share of all running instances for 
 *               a cluster or machine.
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/03/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @MemoryShare TABLE ( SrvrInstncId int          NOT NULL PRIMARY KEY CLUSTERED, 
                                  MachineName  varchar(128) NOT NULL,
                                  MemoryShare  decimal(5,1) NOT NULL, 
                                  MinMemMB     int              NULL, 
                                  MaxMemMB     int              NULL )

     DECLARE @Machine TABLE ( MachineId             int          NOT NULL PRIMARY KEY CLUSTERED, 
                              MachineName           varchar(128) NOT NULL, 
                              TotalMachineMemoryMB  int              NULL, 
                              RSVDMachineMemoryMB   int              NULL,
                              AvailableMemoryMB     int              NULL,
                              TotalSharesForMachine decimal(5,1)     NULL,
                              MBPerShare            int              NULL )

     -- Get memory shares configuration
     INSERT @MemoryShare
          ( SrvrInstncId, 
            MachineName,
            MemoryShare )
     SELECT DISTINCT 
            t.SrvrInstncId,
            t.MachineName,
            MemoryShare = COALESCE( simmc.MemoryShare, 1.0 )
     FROM   tempdb.dbo.tempMSSQLRunningMachine t
            LEFT OUTER JOIN dbo.SrvrInstncMemoryCfgMSSQL simmc
               ON t.SrvrInstncId = simmc.SrvrInstncId
     WHERE  t.SrvrInstncId       != -1
     AND    t.PackageExecutionId  = @PackageExecutionId

     INSERT @Machine
          ( MachineId, 
            MachineName,
            TotalMachineMemoryMB,
            RSVDMachineMemoryMB,
            AvailableMemoryMB )
     SELECT DISTINCT 
            m.MachineId,
            t.MachineName,
            m.TotalMachineMemoryMB,
            m.RSVDMachineMemoryMB,
            m.TotalMachineMemoryMB - m.RSVDMachineMemoryMB
     FROM   dbo.Machine                        m,
            tempdb.dbo.tempMSSQLRunningMachine t
     WHERE  ( m.MachineName      = t.MachineName
           OR m.FQMachineName    = t.MachineName )
     AND    t.PackageExecutionId = @PackageExecutionId

     -- Verify that we have a record for all machine names identified
     IF EXISTS ( SELECT 'X'
                 FROM   tempdb.dbo.tempMSSQLRunningMachine t
                 WHERE  NOT EXISTS ( SELECT 'X'
                                     FROM   @Machine m
                                     WHERE  m.MachineName = t.MachineName )
                 AND    t.SrvrInstncId       != -1
                 AND    t.PackageExecutionId  = @PackageExecutionId )
     BEGIN -- We have at least one machine that was not matched so we are unable
           -- to reliably set server instance memory.
          RAISERROR( 'We were unable to find machine matches for all servers.  Unable to continue!', 16, 1 )
          PRINT 'Matched List'
          SELECT * FROM @Machine
          RETURN 1
     END

     -- Get total shares allocated and MB per share
     UPDATE @Machine 
     SET    TotalSharesForMachine = ms.TotalMemoryShare,
            MBPerShare            = m.AvailableMemoryMB / ms.TotalMemoryShare
     FROM   @Machine m,
            ( SELECT MachineName, TotalMemoryShare = SUM( MemoryShare )
              FROM   @MemoryShare
              GROUP BY MachineName ) ms
     WHERE   m.MachineName = ms.MachineName

     -- Assign Memory to SQL Instances.
     UPDATE @MemoryShare
     SET    MinMemMB = ( ms.MemoryShare * m.MBPerShare ) * 0.25,
            MaxMemMB = ms.MemoryShare * m.MBPerShare
     FROM   @Machine m INNER JOIN @MemoryShare ms
               ON m.MachineName = ms.MachineName 

     IF ( @DebugFlag = 1 )
     BEGIN
          PRINT '@Machine'
          SELECT * FROM @Machine

          PRINT '@MemoryShare'
          SELECT * FROM @MemoryShare
     END

     SELECT SrvrInstncId, 
            MinMemMB, 
            MaxMemMB, 
            MachineName, 
            MemoryShare
     FROM   @MemoryShare
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Calculates the min and max memory for all SQL instances in a SQL cluster or ', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = GenMSSQLMemory;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GenMSSQLMemoryWork' AND type = 'P')
     DROP PROCEDURE dbo.GenMSSQLMemoryWork
GO

CREATE PROCEDURE dbo.GenMSSQLMemoryWork
     @PackageExecutionId tinyint,
     @CleanupFlag        tinyint = 0
AS
/*
 *
 * GenMSSQLMemoryWork
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/03/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @TableExistsFlag tinyint,
             @DropTableFlag   tinyint,
             @CreateTableFlag tinyint,
             @RC              int

     CREATE TABLE #Output ( RecCnt int NOT NULL )

     -- Get whether the table exists
     IF EXISTS ( SELECT 'X' FROM tempdb.sys.tables WHERE name = 'tempMSSQLRunningMachine' AND schema_id = 1 AND type = 'U' )
     BEGIN
          PRINT 'Process Table Exists'
          SET @TableExistsFlag = 1
     END
     ELSE 
     BEGIN
          SET @TableExistsFlag = 0
     END

     -- What mode are we running in..
     IF ( @CleanupFlag = 1 ) 
     BEGIN -- Perform cleanup
          PRINT 'Cleanup Process'
          DECLARE @Cmd           varchar(255),
                  @RecCnt        int

          IF ( @TableExistsFlag = 0 )
          BEGIN -- we don't need to cleanup since there are no records and no table
               DROP TABLE #Output
               PRINT 'No cleanup required.'
               RETURN 
          END
          ELSE
          BEGIN -- A table exists, we will see how much cleanup is needed, just 
                -- a removal of records or a table too..
               -- Remove records for this PackageExecutionId
               PRINT 'Cleaning up records for this process.'

               DELETE FROM tempdb.dbo.tempMSSQLRunningMachine WHERE PackageExecutionId = @PackageExecutionId

               -- Lets see if there is any other process that might have used the table and is in process.
               INSERT #Output ( RecCnt ) EXEC ( 'SELECT COUNT(*) FROM tempdb.dbo.tempMSSQLRunningMachine WHERE CrDt > DATEADD( mi, -15, CURRENT_TIMESTAMP )' )
               SELECT @RecCnt = RecCnt FROM #Output
               SELECT @RecCnt = ISNULL( @RecCnt, 0 )

               IF ( @RecCnt > 0 )
               BEGIN -- We have a record less than 15 
                    SET @DropTableFlag = 0
               END
               ELSE
               BEGIN
                    SET @DropTableFlag = 1
               END
          END
     END
     ELSE 
     BEGIN
          PRINT 'Build Process'
          IF ( @TableExistsFlag = 1 )
          BEGIN -- Table does exist, determine if this is a drop/create scenario
               INSERT #Output ( RecCnt ) EXEC ( 'SELECT COUNT(*) FROM tempdb.dbo.tempMSSQLRunningMachine WHERE CrDt > DATEADD( mi, -15, CURRENT_TIMESTAMP )' )
               SELECT @RecCnt = RecCnt FROM #Output
               SELECT @RecCnt = ISNULL( @RecCnt, 0 )

               IF ( @RecCnt > 0 )
               BEGIN -- We have a record less than 15m, so we leave the table alone.
                    SET @DropTableFlag = 0
                    SET @CreateTableFlag = 0
               END
               ELSE
               BEGIN -- We do a drop/create
                    SET @DropTableFlag = 1
                    SET @CreateTableFlag = 1
               END
          END
          ELSE
          BEGIN -- table doesn't exist so no drop
               SET @CreateTableFlag = 1
          END
     END

     IF ( @DropTableFlag = 1 )
     BEGIN
          PRINT 'Dropping Table'
          EXEC ( 'DROP TABLE tempdb.dbo.tempMSSQLRunningMachine' )

          IF EXISTS ( SELECT 'X' FROM tempdb.sys.tables WHERE name = 'tempMSSQLRunningMachine' AND schema_id = 1 AND type = 'U' )
          BEGIN
               PRINT 'Table Drop Failed'
               IF ( @CreateTableFlag = 1 )
               BEGIN
                    PRINT 'Overriding Create Table Flag'
                    SET @CreateTableFlag = 0
               END
               ELSE
               BEGIN
                    DROP TABLE #Output
                    RAISERROR( 'Error! Process working table tempMSSQLRunningMachine still exists!', 16, 1 )
                    RETURN 1
               END 
          END     
     END

     IF ( @CreateTableFlag = 1 )
     BEGIN -- Create it
          PRINT 'Creating Table'
          EXEC ( 'CREATE TABLE tempdb.dbo.tempMSSQLRunningMachine ( PackageExecutionId BIGINT NOT NULL, SrvrInstncId INT NOT NULL, MachineName varchar(128) NOT NULL, CrDt datetime NULL )' )

          -- Immediately insert record
          PRINT 'Inserting Process Record'
          INSERT tempdb.dbo.tempMSSQLRunningMachine
               ( PackageExecutionId,
                 SrvrInstncId,
                 MachineName, 
                 CrDt )
          SELECT @PackageExecutionId,
                 -1, 
                 '',
                 CURRENT_TIMESTAMP

          -- Verify working table existence
          IF NOT EXISTS ( SELECT 'X' FROM tempdb.sys.tables WHERE name = 'tempMSSQLRunningMachine' AND schema_id = 1 AND type = 'U' )
          BEGIN
               DROP TABLE #Output
               RAISERROR( 'Error! Process working table tempMSSQLRunningMachine does not exist!', 16, 1 )
               RETURN 1
          END     
     END

     DROP TABLE #Output
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Creates, recreates, or deletes the persisted temp table in tempdb used for setting memory limits for MSSQL Instances in a cluster.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = GenMSSQLMemoryWork;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetDBConnectionString' AND type = 'P')
     DROP PROCEDURE dbo.GetDBConnectionString
GO

CREATE PROCEDURE dbo.GetDBConnectionString
     @SrvrInstncId     int, 
     @DatabaseName     varchar(128)    = NULL,
     @ConnectionString varchar(8000)   = NULL OUTPUT,
     @CipherTextString varbinary(1024) = NULL OUTPUT
AS
/*
 *
 * GetDBConnectionString
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      A Cleartext connection string
 *
 * Note(s):      This version is a stub, it contains no differentiation logic
 *               for any of the different server types and currently only builds
 *               trusted connection strings for MSSQL.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2010, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Log sproc use.  Starting
     EXEC dbo.InsEventLog @EventLogTypeId = 1, -- Informational
                          @LogByApp       = 'GetDBConnectionString',
                          @LogByDesc      = 'Standard',
                          @LogText        = 'GetDBConnectionString Starting',
                          @MiscInt1       = @SrvrInstncId,
                          @MiscVC1        = @DatabaseName

     DECLARE @SrvrInstncTypeId     int,
             @SrvrInstncName       varchar(128),
             @OLEDBProviderName    varchar(128)

     SET @CipherTextString = NULL
     
     IF ( @DatabaseName IS NULL )
     BEGIN
          SET @DatabaseName = 'master'
     END

     -- Get basic server information
     SELECT @SrvrInstncName      = i.SrvrInstncFullName,
            @SrvrInstncTypeId    = t.SrvrInstncTypeId,
            @OLEDBProviderName   = t.OLEDBProviderName 
     FROM   dbo.SrvrInstnc i INNER JOIN dbo.SrvrInstncType t
               ON i.SrvrInstncTypeId = t.SrvrInstncTypeId 
     WHERE  SrvrInstncId = @SrvrInstncId 

     SELECT @ConnectionString = dbo.GenConnectionString( 1, @SrvrInstncName, @DatabaseName, NULL, NULL, @OLEDBProviderName, NULL )
     
     -- Log ending..
     EXEC dbo.InsEventLog @EventLogTypeId = 1, -- Informational
                          @LogByApp       = 'GetDBConnectionString',
                          @LogText        = 'GetDBConnectionString Ending',
                          @LogByDesc      = 'Standard',
                          @MiscInt1       = @SrvrInstncId,
                          @MiscInt2       = NULL, -- @SrvrInstncCredTypeId,
                          @MiscVC1        = @DatabaseName

     -- Return it..
     SELECT ConnectionString = @ConnectionString,
            CipherTextString = @CipherTextString 
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Get a conenction string for a specified server instance id.  This is the standard version that does not handle any form of encryption.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = GetDBConnectionString;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'GetServerListForGetServerInfo' AND type = 'P')
     DROP PROCEDURE dbo.GetServerListForGetServerInfo
GO

CREATE PROCEDURE dbo.GetServerListForGetServerInfo
     @SrvrInstncGrpId int = NULL 
AS
/*
 *
 * GetServerListForGetServerInfo
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/22/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Log sproc use.  Starting
     EXEC dbo.InsEventLog @EventLogTypeId = 1, -- Informational
                          @LogByApp       = 'GetServerListForGetServerInfo',
                          @LogText        = 'GetServerListForGetServerInfo Starting',
                          @MiscInt1       = @SrvrInstncGrpId

     DECLARE @RC int 

     -- Condition SrvrInstncGrpId 
     SELECT @SrvrInstncGrpId = CASE WHEN @SrvrInstncGrpId IS NULL
                                    THEN NULL
                                    WHEN @SrvrInstncGrpId = 0
                                    THEN NULL
                                    WHEN @SrvrInstncGrpId < 0
                                    THEN NULL
                                    WHEN @SrvrInstncGrpId > 0
                                    THEN @SrvrInstncGrpId
                               END

     -- Verify Group
     IF   ( @SrvrInstncGrpId IS NOT NULL
        AND NOT EXISTS ( SELECT 'X'
                         FROM   dbo.SrvrInstncGrp sig
                         WHERE  sig.SrvrInstncGrpId = @SrvrInstncGrpId )
          )
     BEGIN
          EXEC dbo.InsEventLog @EventLogTypeId = 3, -- Error
                               @LogByApp       = 'GetServerListForGetServerInfo',
                               @LogText        = 'GroupId was not found.',
                               @MiscInt1       = @SrvrInstncGrpId
          RAISERROR( 'GroupId was not found.', 16, 1 )
     END
     ELSE
     BEGIN
          -- Return the results.
          SELECT SrvrInstncId,
                 SrvrInstncTypeId,
                 SrvrInstncFullName
          FROM   dbo.SrvrInstnc si
          WHERE  si.EnabledFlag = 1
          AND  ( si.SrvrInstncGrpId = @SrvrInstncGrpId
              OR @SrvrInstncGrpId   IS NULL )

          SELECT @RC = @@ROWCOUNT
     END
     
     -- Log ending..
     EXEC dbo.InsEventLog @EventLogTypeId = 1, -- Informational
                          @LogByApp       = 'GetServerListForGetServerInfo',
                          @LogText        = 'GetServerListForGetServerInfo Ending',
                          @MiscInt1       = @SrvrInstncGrpId,
                          @MiscInt2       = @RC
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Returns a list of servers for the GetServerInfo package.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = GetServerListForGetServerInfo;
GO
IF EXISTS ( SELECT 'X' FROM sys.procedures WHERE name = 'InsDDLActivity' AND schema_id = 1 )
BEGIN
     IF EXISTS ( SELECT 'X' 
                 FROM   sys.server_triggers 
                 WHERE  parent_class_desc = 'SERVER' 
                 AND    name              = 'LogAllDDL' 
                 AND    is_disabled       = 0 )
     BEGIN
          EXEC( 'DISABLE TRIGGER [LogAllDDL] ON ALL SERVER' )
     END

     DROP PROCEDURE dbo.InsDDLActivity
END
GO

CREATE PROCEDURE dbo.InsDDLActivity
     @EventData xml 
WITH ENCRYPTION 
AS
/*
 *
 * InsDDLActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/29/2009, 1.00.0000
 *
 */
BEGIN
     SET XACT_ABORT ON
     SET NOCOUNT ON
     SET CONCAT_NULL_YIELDS_NULL ON

     INSERT dbo.EventLog
          ( EventLogTypeId,
            LogDt,
            LoginName,
            DatabaseUserName,
            DatabaseName,
            AppName,
            SPID,
            SID,
            LogByApp,
            LogByAppSubSystem,
            LogByDesc,
            LogText,
            TraceText,
            MiscVC1,
            MiscVC2,
            MiscVC3,
            MiscVC4 )
     SELECT 1, -- EventLogTypeId
            @EventData.value('(/EVENT_INSTANCE/PostTime)[1]', 'datetime'),
            @EventData.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(128)'),
            @EventData.value('(/EVENT_INSTANCE/UserName)[1]', 'nvarchar(128)'),
            @EventData.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'nvarchar(128)'),
            APP_NAME(),
            @EventData.value('(/EVENT_INSTANCE/SPID)[1]', 'int'),
            SUSER_SID(@EventData.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(128)')),
            'LogAllDDL', -- LogByApp
            'InsDDLActivity', -- LogByAppSubSystem
            '', -- LogByDesc
            '', -- LogText
            @EventData.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(max)'),
            @EventData.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(128)'),
            @EventData.value('(/EVENT_INSTANCE/SchemaName)[1]', 'nvarchar(128)'),
            @EventData.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(128)'),
            @EventData.value('(/EVENT_INSTANCE/ObjectType)[1]', 'nvarchar(128)')            
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a DDL activity row into the EventLog table, this sproc is called from the Server Level ddl trigger.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsDDLActivity;
GO

GRANT EXEC ON dbo.InsDDLActivity TO AuditCredUser
GO

-- Enable the trigger
IF EXISTS ( SELECT 'X' 
            FROM   sys.server_triggers 
            WHERE  parent_class_desc = 'SERVER' 
            AND    name              = 'LogAllDDL' 
            AND    is_disabled       = 1 )
BEGIN
     EXEC ( 'ENABLE TRIGGER [LogAllDDL] ON ALL SERVER' )
END
GO
IF EXISTS ( SELECT 'X' FROM sys.procedures WHERE name = 'InsEventLog' AND schema_id = 1 )
BEGIN
     DROP PROCEDURE dbo.InsEventLog
END
GO

CREATE PROCEDURE dbo.InsEventLog
     @EventLogTypeId    int              = 0, -- Unknown
     @LogByApp          varchar(128)     = NULL,
     @LogByAppSubSystem varchar(128)     = NULL,
     @LogByDesc         varchar(128)     = NULL,
     @LogText           varchar(6144)    = NULL,
     @TraceText         varchar(max)     = NULL,
     @TraceImage        varbinary(max)   = NULL,
     @SID               varbinary(85)    = NULL,
     @MiscVC1           varchar(128)     = NULL,
     @MiscVC2           varchar(128)     = NULL,
     @MiscVC3           varchar(128)     = NULL,
     @MiscVC4           varchar(128)     = NULL,
     @MiscInt1          int              = NULL,
     @MiscInt2          int              = NULL,
     @MiscInt3          int              = NULL,
     @MiscInt4          int              = NULL,
     @MiscTinyInt1      tinyint          = NULL,
     @MiscTinyInt2      tinyint          = NULL,
     @MiscTinyInt3      tinyint          = NULL,
     @MiscTinyInt4      tinyint          = NULL,
     @MiscBigInt1       bigint           = NULL,
     @MiscBigInt2       bigint           = NULL,
     @MiscBigInt3       bigint           = NULL,
     @MiscBigInt4       bigint           = NULL,
     @MiscDt1           datetime         = NULL,
     @MiscDt2           datetime         = NULL,
     @MiscDt3           datetime         = NULL,
     @MiscDt4           datetime         = NULL,
     @MiscGUID1         uniqueidentifier = NULL,
     @MiscGUID2         uniqueidentifier = NULL,
     @MiscGUID3         uniqueidentifier = NULL,
     @MiscGUID4         uniqueidentifier = NULL
AS
/*
 *
 * InsEventLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/29/2009, 1.00.0000
 *
 */
BEGIN
     SET XACT_ABORT ON
     SET NOCOUNT ON

     IF NOT EXISTS ( SELECT 'X' 
                     FROM   dbo.EventLogType
                     WHERE  EventLogTypeId = @EventLogTypeId )
     BEGIN -- Force it to unknown, we'd rather get the event than lose it.
          SELECT @EventLogTypeId = 0 
     END
     
     INSERT dbo.EventLog
          ( EventLogTypeId,
            LogByApp,
            LogByAppSubSystem,
            LogByDesc,
            LogText,
            TraceText,
            TraceImage,
            SID,
            MiscVC1,
            MiscVC2,
            MiscVC3,
            MiscVC4,
            MiscInt1,
            MiscInt2,
            MiscInt3,
            MiscInt4,
            MiscTinyInt1,
            MiscTinyInt2,
            MiscTinyInt3,
            MiscTinyInt4,
            MiscBigInt1,
            MiscBigInt2,
            MiscBigInt3,
            MiscBigInt4,
            MiscDt1,
            MiscDt2,
            MiscDt3,
            MiscDt4,
            MiscGUID1,
            MiscGUID2,
            MiscGUID3,
            MiscGUID4 )
     SELECT @EventLogTypeId,
            @LogByApp,
            @LogByAppSubSystem,
            @LogByDesc,
            @LogText,
            @TraceText,
            @TraceImage,
            @SID,
            @MiscVC1,
            @MiscVC2,
            @MiscVC3,
            @MiscVC4,
            @MiscInt1,
            @MiscInt2,
            @MiscInt3,
            @MiscInt4,
            @MiscTinyInt1,
            @MiscTinyInt2,
            @MiscTinyInt3,
            @MiscTinyInt4,
            @MiscBigInt1,
            @MiscBigInt2,
            @MiscBigInt3,
            @MiscBigInt4,
            @MiscDt1,
            @MiscDt2,
            @MiscDt3,
            @MiscDt4,
            @MiscGUID1,
            @MiscGUID2,
            @MiscGUID3,
            @MiscGUID4
END
GO

GRANT EXEC ON dbo.InsEventLog TO guest
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts an event entry into the EventLog table.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsEventLog;
GO
IF EXISTS ( SELECT 'X' FROM sys.procedures WHERE name = 'InsLogonActivity' AND schema_id = 1 )
BEGIN
     IF EXISTS ( SELECT 'X' 
                 FROM   sys.server_triggers 
                 WHERE  parent_class_desc = 'SERVER' 
                 AND    name              = 'LogAllLogons' 
                 AND    is_disabled       = 0 )
     BEGIN
          EXEC( 'DISABLE TRIGGER [LogAllLogons] ON ALL SERVER' )
     END

     DROP PROCEDURE dbo.InsLogonActivity
END
GO

CREATE PROCEDURE dbo.InsLogonActivity
     @EventData xml 
WITH ENCRYPTION 
AS
/*
 *
 * InsLogonActivity
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/29/2009, 1.00.0000
 *
 */
BEGIN
     SET XACT_ABORT ON
     SET NOCOUNT ON
     
     DECLARE @SPID               int,
             @net_transport      varchar(40),
             @client_net_address varchar(48)

     SELECT @SPID = @EventData.value('(/EVENT_INSTANCE/SPID)[1]', 'int')

     SELECT @net_transport      = net_transport,
            @client_net_address = client_net_address
     FROM   sys.dm_exec_connections 
     WHERE  session_id = @SPID

     INSERT dbo.EventLog
          ( EventLogTypeId,
            HostName,
            LoginName,
            DatabaseUserName,
            DatabaseName,
            AppName,
            SPID,
            SID,
            LogByApp,
            LogByAppSubSystem,
            LogByDesc,
            LogText,
            MiscVC1,
            MiscVC2,
            MiscDt1,
            MiscTinyint1 )
     SELECT 1, -- EventLogTypeId
            HostName = CASE WHEN @EventData.value('(/EVENT_INSTANCE/ClientHost)[1]', 'nvarchar(128)') = N'<local machine>'
                            THEN HOST_NAME()
                            ELSE @EventData.value('(/EVENT_INSTANCE/ClientHost)[1]', 'nvarchar(128)')
                       END,
            @EventData.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(128)'),
            NULL, -- DatabaseUserName,
            NULL, -- DatabaseName
            APP_NAME(),
            @EventData.value('(/EVENT_INSTANCE/SPID)[1]', 'int'),
            @EventData.value('(/EVENT_INSTANCE/SID)[1]', 'varbinary(85)'),
            'LogAllLogon', -- LogByApp
            'InsLogonActivity', -- LogByAppSubSystem
            '', -- LogByDesc
            '', -- LogText
            @net_transport,
            MiscVC2 = CASE WHEN @client_net_address = '<local machine>'
                           THEN HOST_NAME()
                           ELSE @client_net_address
                      END,
            @EventData.value('(/EVENT_INSTANCE/PostTime)[1]', 'datetime'),
            @EventData.value('(/EVENT_INSTANCE/IsPooled)[1]', 'tinyint')
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a logon activity row into the EventLog table, this sproc is called from the Server Level logon trigger.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsLogonActivity;
GO

GRANT EXEC ON dbo.InsLogonActivity TO AuditCredUser
GO

-- Enable the trigger
IF EXISTS ( SELECT 'X' 
            FROM   sys.server_triggers 
            WHERE  parent_class_desc = 'SERVER' 
            AND    name              = 'LogAllLogons' 
            AND    is_disabled       = 1 )
BEGIN
     EXEC ( 'ENABLE TRIGGER [LogAllLogons] ON ALL SERVER' )
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'InsMachineDriveVolumeSpace' AND type = 'P')
     DROP PROCEDURE dbo.InsMachineDriveVolumeSpace
GO

CREATE PROCEDURE dbo.InsMachineDriveVolumeSpace
     @MachineId                int,
     @PackageExecutionId       bigint,
     @MachineDriveVolumeId     int,
     @VolumeDeviceId           varchar(128),
     @VolumeCapacity           bigint,
     @VolumeFreeSpace          bigint,
     @PackageExecutionIdStr    varchar(30)   = NULL
AS
/*
 *
 * InsMachineDriveVolumeSpace
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/02/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Early bail point, for cases where the capacity is NULL, we have a drive 
     -- but the OS does not know its size, so we record the drive but not its
     -- capacity or available space.  We bail here before we do any additional 
     -- processing because we know the record won't be inserted later.
     IF ( @VolumeCapacity IS NULL )
     BEGIN
          RETURN 0
     END

     DECLARE @MinTime        int,
             @VolumeIdForSrv int,
             @PEI            bigint,
             @RC             int,
             @NOW            datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Handle case of PackageExecutionId
     IF ( @PackageExecutionId IS NULL AND @PackageExecutionIdStr IS NOT NULL )
     BEGIN -- Id value ALWAYS takes precedence
          SELECT @PackageExecutionId = CONVERT( bigint, @PackageExecutionIdStr )
     END
     ELSE 
     BEGIN -- All other cases we set the string to match the id
          SELECT @PackageExecutionIdStr = CONVERT( varchar(30), @PackageExecutionId )
     END

     -- We may have the DeviceId or the direct id to the volume, if we have the 
     -- volume id it takes precedence.  If not we need to look it up.
     IF ( @MachineDriveVolumeId IS NULL AND @VolumeDeviceId IS NOT NULL )
     BEGIN -- We need to calc the volume id for the server instance
          SELECT @VolumeIdForSrv = MachineDriveVolumeId 
          FROM   dbo.MachineDriveVolume
          WHERE  MachineId      = @MachineId 
          AND    VolumeDeviceId = @VolumeDeviceId
     END
     ELSE
     BEGIN -- We use a little trick here and assume something was passed, we'll 
           -- make sure in a bit.
          SET @VolumeIdForSrv = @MachineDriveVolumeId
     END

     IF ( @VolumeIdForSrv IS NULL )
     BEGIN
          EXEC dbo.InsEventLog 
                    @EventLogTypeId    = 3, -- Error
                    @LogByApp          = 'InsMachineDriveVolumeSpace',
                    @LogByAppSubSystem = NULL,
                    @LogByDesc         = NULL,
                    @LogText           = 'Could not determine the server instance volume id from the passed values, record insertion failed!',
                    @MiscVC1           = @VolumeDeviceId,
                    @MiscInt1          = @MachineId,
                    @MiscInt2          = @MachineDriveVolumeId,
                    @MiscBigInt1       = @PackageExecutionId,
                    @MiscBigInt2       = @VolumeCapacity,
                    @MiscBigInt3       = @VolumeFreeSpace

          RAISERROR( 'Could not determine the server instance volume id from the passed values, record insertion failed!', 16, 1 )

          RETURN 1
     END

     -- Before we do the insert we have one last check, to keep there from being
     -- too many samples we won't write a sample less than 55 minutes from the 
     -- last sample.

     -- Get the configured time
     SELECT @MinTime = ISNULL( dbo.GetCfgCtrlKeyAsInt( 'MinMinutesBetweenVolSpcSamples' ), 55 )

     IF NOT EXISTS ( SELECT 'X' 
                     FROM   dbo.MachineDriveVolumeSpace 
                     WHERE  MachineId            = @MachineId
                     AND    MachineDriveVolumeId = @VolumeIdForSrv
                     AND    CaptureDt            > DATEADD( mi, -1 * @MinTime, @NOW ) )
     BEGIN
          -- Do the insert, the used space gets calculated and stored in real-time so
          -- we don't have to handle that.  Also the two flags are not set by this
          -- process, that functionality is handled elsewhere, the purpose here is
          -- to get the data inserted.
          INSERT dbo.MachineDriveVolumeSpace
               ( MachineId,
                 MachineDriveVolumeId,
                 CaptureDt,
                 PackageExecutionId,
                 VolumeCapacityBytes,
                 VolumeFreeSpaceBytes )
          SELECT @MachineId,
                 @VolumeIdForSrv,
                 @NOW, -- CaptureDt
                 @PackageExecutionId,
                 @VolumeCapacity,
                 @VolumeFreeSpace
     END
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'InsMSSQLMemoryWork' AND type = 'P')
     DROP PROCEDURE dbo.InsMSSQLMemoryWork
GO

CREATE PROCEDURE dbo.InsMSSQLMemoryWork
     @PackageExecutionId tinyint,
     @SrvrInstncId       int, 
     @MachineName        varchar(128)
AS
/*
 *
 * InsMSSQLMemoryWork
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/03/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     IF EXISTS ( SELECT 'X'
                 FROM   tempdb.dbo.tempMSSQLRunningMachine
                 WHERE  PackageExecutionId = @PackageExecutionId
                 AND    SrvrInstncId       = @SrvrInstncId )
     BEGIN -- Update record
          UPDATE tempdb.dbo.tempMSSQLRunningMachine
          SET    MachineName = @MachineName
          FROM   tempdb.dbo.tempMSSQLRunningMachine
          WHERE  PackageExecutionId = @PackageExecutionId
          AND    SrvrInstncId       = @SrvrInstncId           
     END
     ELSE 
     BEGIN -- Insert Record
          INSERT tempdb.dbo.tempMSSQLRunningMachine
               ( PackageExecutionId,
                 SrvrInstncId,
                 MachineName, 
                 CrDt )
          SELECT @PackageExecutionId,
                 @SrvrInstncId, 
                 @MachineName,
                 CURRENT_TIMESTAMP
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a record in the persisted temp table in tempdb used for setting memory limits for MSSQL Instances in a cluster.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsMSSQLMemoryWork;
GO
IF EXISTS ( SELECT 'X' FROM sys.procedures WHERE name = 'InsPackageExecutionLog' AND schema_id = 1 )
BEGIN
     DROP PROCEDURE dbo.InsPackageExecutionLog
END
GO

CREATE PROCEDURE dbo.InsPackageExecutionLog
     @PackageName                 nvarchar(255),
     @PackageExecutionGUID        varchar(38),
     @PackageMajorVersion         int,
     @PackageMinorVersion         int,
     @PackageBuildVersion         int,
     @MachineName                 nvarchar(128),
     @UserName                    nvarchar(128),
     @ContainerStartTime          datetime,
     @PackageStartTime            datetime,
     @PackageStartingFlag         tinyint       = 0, -- When both are zero it is 
     @PackageEndingFlag           tinyint       = 0, -- an info message.
     @ParentPackageExecutionId    bigint        = NULL,
     @ParentPackageExecutionIdStr varchar(30)   = NULL,
     @LogText                     varchar(6144) = NULL,
     @PackageExecutionId          bigint        = NULL OUTPUT,
     @PackageExecutionIdStr       varchar(30)   = NULL OUTPUT
AS
/*
 *
 * InsPackageExecutionLog
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/29/2009, 1.00.0000
 *
 */
BEGIN
     SET XACT_ABORT ON
     SET NOCOUNT ON

     -- Handle case of PackageExecutionId
     IF ( @PackageExecutionId IS NULL AND @PackageExecutionIdStr IS NOT NULL )
     BEGIN -- Id value ALWAYS takes precedence
          SELECT @PackageExecutionId = CONVERT( bigint, @PackageExecutionIdStr )
     END
     ELSE 
     BEGIN -- All other cases we set the string to match the id
          SELECT @PackageExecutionIdStr = CONVERT( varchar(30), @PackageExecutionId )
     END
     
     -- Handle case of ParentPackageExecutionId
     IF ( @ParentPackageExecutionId IS NULL AND @ParentPackageExecutionIdStr IS NOT NULL )
     BEGIN -- Id value ALWAYS takes precedence
          SELECT @ParentPackageExecutionId = CONVERT( bigint, @ParentPackageExecutionIdStr )
     END
     ELSE 
     BEGIN -- All other cases we set the string to match the id
          SELECT @ParentPackageExecutionIdStr = CONVERT( varchar(30), @ParentPackageExecutionId )
     END

     -- Condition Flags
     SELECT @PackageStartingFlag = CASE WHEN @PackageStartingFlag NOT IN ( 0, 1 )
                                        THEN 0
                                        ELSE @PackageStartingFlag
                                   END,
            @PackageEndingFlag   = CASE WHEN @PackageEndingFlag NOT IN ( 0, 1 )
                                        THEN 0
                                        ELSE @PackageEndingFlag
                                   END
     -- Handle Invalid flag combinations..
     SELECT @PackageStartingFlag = CASE WHEN @PackageStartingFlag = 1
                                         AND @PackageEndingFlag   = 1
                                        THEN 0
                                        ELSE @PackageStartingFlag
                                   END,
            @PackageEndingFlag   = CASE WHEN @PackageStartingFlag = 1
                                         AND @PackageEndingFlag   = 1
                                        THEN 0
                                        ELSE @PackageEndingFlag
                                   END

     -- Get the next package execution id from the SEQ table.  We do the an 
     -- optimistic commit with the expectation that the insert will succeed.
     -- given the way the insert occurs this is likely.  We do the commit 
     -- this way for concurrency reasons.  I don't wish to hold the lock any
     -- longer than I need to.
     IF ( @PackageStartingFlag = 1 )
     BEGIN
          BEGIN TRANSACTION

          UPDATE dbo.Seq 
          SET    SeqNumber = SeqNumber + 0 -- Lock record for a moment..
          WHERE  SeqName = 'PackageExecutionId'

          SELECT @PackageExecutionId = SeqNumber + 1
          FROM   dbo.Seq
          WHERE  SeqName = 'PackageExecutionId'
          
          UPDATE dbo.Seq
          SET   SeqNumber = @PackageExecutionId 
          FROM   dbo.Seq
          WHERE  SeqName = 'PackageExecutionId'

          COMMIT TRANSACTION
     END
     
     -- Insert it.
     INSERT dbo.EventLog 
          ( EventLogTypeId,
            LogByApp,
            LogByAppSubSystem,
            LogByDesc,
            LogText,
            MiscVC1,
            MiscVC2,
            MiscInt1,
            MiscInt2,
            MiscInt3,
            MiscBigInt1,
            MiscBigInt2,
            MiscDt1,
            MiscDt2,
            MiscDt3,
            MiscGUID4,
            MiscTinyInt1 )
     SELECT 1, -- EventLogTypeId
            'Integration Services', -- LogByApp
            'InsPackageExecutionLog', -- LogByAppSubSystem
            CONVERT( varchar(128), @PackageName ), -- LogByDesc
            LogText = CASE WHEN @PackageStartingFlag = 1
                            AND @PackageEndingFlag   = 0
                           THEN 'Package Starting'
                           WHEN @PackageStartingFlag = 0
                            AND @PackageEndingFlag   = 0
                           THEN @LogText 
                           WHEN @PackageStartingFlag = 0
                            AND @PackageEndingFlag   = 1
                           THEN 'Package Ending'
                           ELSE 'Package Action Unknown' -- Should not happen
                      END,
            CONVERT( varchar(128), @MachineName ), -- MiscVC1
            CONVERT( varchar(128), @UserName ), -- MiscVC2
            @PackageMajorVersion, -- MiscInt1
            @PackageMinorVersion, -- MiscInt2
            @PackageBuildVersion, -- MiscInt3
            MiscBigInt1 = @PackageExecutionId,
            MiscBigInt2 = CASE WHEN @ParentPackageExecutionId = -1
                               THEN NULL
                               ELSE @ParentPackageExecutionId
                          END, -- MiscBigInt2
            @ContainerStartTime, -- MiscDt1
            @PackageStartTime, -- MiscDt2
            MiscDt3 = CASE WHEN @PackageEndingFlag = 0
                           THEN NULL
                           WHEN @PackageEndingFlag = 1
                           THEN CURRENT_TIMESTAMP 
                           ELSE NULL -- Should not happen
                      END,
            @PackageExecutionGUID, -- MiscGUID4
            MiscTinyInt1 = CASE WHEN @PackageStartingFlag = 1
                                 AND @PackageEndingFlag   = 0
                                THEN 1 -- Start
                                WHEN @PackageStartingFlag = 0
                                 AND @PackageEndingFlag   = 0
                                THEN 128 -- Info Message
                                WHEN @PackageStartingFlag = 0
                                 AND @PackageEndingFlag   = 1
                                THEN 255 -- End
                                ELSE NULL -- Should not happen
                           END

     -- Get the value for the output variable and use it on the return
     SELECT @PackageExecutionId = CONVERT(bigint, @PackageExecutionId )
     SELECT @PackageExecutionIdStr = CONVERT( varchar(30), @PackageExecutionId )
          
     -- Return it
     SELECT PackageExecutionId          = @PackageExecutionId,
            PackageExecutionIdStr       = @PackageExecutionIdStr,
            ParentPackageExecutionId    = @ParentPackageExecutionId,
            ParentPackageExecutionIdStr = @ParentPackageExecutionIdStr,
            PackageStartingFlag         = @PackageStartingFlag,
            PackageEndingFlag           = @PackageEndingFlag
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a SSIS package execution record into EventLog and returns a PackageExecutionId for the package to use.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsPackageExecutionLog;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'InsSrvrInstnc' AND type = 'P')
     DROP PROCEDURE dbo.InsSrvrInstnc
GO

CREATE PROCEDURE dbo.InsSrvrInstnc
     @SrvrInstncFullName varchar(255),
     @SrvrInstncTypeId   int,
     @SrvrInstncGrpId    int = 0,
     @SrvrInstncId       int = NULL OUTPUT
AS
/*
 *
 * InsSrvrInstnc
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      SrvrInstncId in both output variable and resultset.
 *
 * Note(s):      
 *
 * CfgCtrl Keys: 
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 04/22/2009, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     SET @SrvrInstncId = NULL

     -- Check parameters.

     -- Check to see if it already exists..
     IF EXISTS ( SELECT 'X' FROM dbo.SrvrInstnc WHERE SrvrInstncFullName = @SrvrInstncFullName )
     BEGIN
          SELECT @SrvrInstncId = SrvrInstncId FROM dbo.SrvrInstnc WHERE SrvrInstncFullName = @SrvrInstncFullName
          
          RAISERROR( 'Specified server instance name already exists.  Cannot add a duplicate.', 16 , 1 )
          RETURN 1
     END
     
     -- Check to see that the TypeId is valid.
     IF NOT EXISTS ( SELECT 'X' FROM dbo.SrvrInstncType WHERE SrvrInstncTypeId = @SrvrInstncTypeId )
     BEGIN
          RAISERROR( 'Specified server instance type does not exist.  Cannot add server instance without a valid type.', 16 , 1 )
          RETURN 1
     END
     
     -- Check to see that the GrpId is valid.
     IF NOT EXISTS ( SELECT 'X' FROM dbo.SrvrInstncGrp WHERE SrvrInstncGrpId = @SrvrInstncGrpId )
     BEGIN
          RAISERROR( 'Specified server instance group does not exist.  Cannot add server instance without a valid group.', 16 , 1 )
          RETURN 1
     END

     -- If you got this far the inputs are valid..  
     BEGIN TRANSACTION

     -- Insert record
     INSERT dbo.SrvrInstnc 
          ( SrvrInstncTypeId,
            SrvrInstncGrpId,
            EnabledFlag,
            SrvrInstncFullName,
            LastModDt )
     SELECT @SrvrInstncTypeId,
            @SrvrInstncGrpId,
            1, -- EnabledFlag
            @SrvrInstncFullName,
            CURRENT_TIMESTAMP

     SELECT @SrvrInstncId = SCOPE_IDENTITY()

     IF ( @SrvrInstncTypeId = 1 ) -- MSSQL
     BEGIN
          INSERT dbo.SrvrInstncMSSQL
               ( SrvrInstncId,
                 SrvrInstncMachineName,
                 SrvrInstncInstanceName )
          SELECT @SrvrInstncId,
                 dbo.GetMachineNameFromMSSQLFullInstanceName( @SrvrInstncFullName ),
                 dbo.GetInstanceNameFromMSSQLFullInstanceName( @SrvrInstncFullName )
     END

     COMMIT

     -- Return resultset
     SELECT SrvrInstncId = @SrvrInstncId 
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Insert a server instance record, this is the basic store procedure for getting nearly all other processes in the repository working.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = InsSrvrInstnc;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'PurgeEventLog' AND type = 'P')
     DROP PROCEDURE dbo.PurgeEventLog
GO

CREATE PROCEDURE dbo.PurgeEventLog
AS
/*
 *
 * PurgeEventLog
 *
 * Purpose:      To remove old entries in the EventLog table
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      Records may be deleted.
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: MaxEventLogDaysToKeep, number of days to keep records, 
 *               MaxEventLogIdCollectedByRepos, highest EventLogId that was
 *               collected by the repository collection process.
 *
 *               Record delete be prevented if the MaxEventLogIdCollectedByRepos
 *               is less than the date range that is to be deleted.  this value 
 *               does not have any effect on the collection process, it exists 
 *               to assist the purge process decide whether it should delete 
 *               records.  The main purpose is to prevent record deletion before
 *               they can be collected.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/11/2009, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     EXEC dbo.InsEventLog @EventLogTypeId     = 1, -- Info
                          @LogByApp           = 'PurgeEventLog',
                          @LogText            = 'Process Starting'

     DECLARE @MaxEventLogDaysToKeep            bigint,
             @RepositoryInUseFlag              tinyint,
             @RepositoryInUseFlagStr           varchar(8000),
             @MaxEventLogIdCollectedByRepos    bigint,
             @MaxEventLogIdForDt               bigint,
             @BeforeEventLogId                 bigint,
             @DeleteBeforeDt                   datetime,
             @msg                              varchar(6144),
             @RC                               bigint

     -- Get stored paramters, but don't use the normal functions, read directly.
     SELECT @MaxEventLogDaysToKeep = CONVERT( int, CfgCtrlValue )
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = 'MaxEventLogDaysToKeep'

     SELECT @MaxEventLogIdCollectedByRepos = CONVERT( bigint, CfgCtrlValue )
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = 'MaxEventLogIdCollectedByRepos'

     SELECT @RepositoryInUseFlagStr = CfgCtrlValue 
     FROM   dbo.CfgCtrl
     WHERE  CfgCtrlKey = 'RepositoryInUseFlag'

     IF ( @RepositoryInUseFlagStr = '1' )
     BEGIN
          SET @RepositoryInUseFlag = 1
     END
     ELSE
     BEGIN
          SET @RepositoryInUseFlag = 0
     END

     -- Figure out what date we are working with..
     SELECT @DeleteBeforeDt = DATEADD( dd, -1 * ISNULL( @MaxEventLogDaysToKeep, 30 ), GETDATE() )

     -- Figure out what EventLogId that date that date range covers.
     SELECT @MaxEventLogIdForDt = MAX(EventLogId) 
     FROM   dbo.EventLog 
     WHERE  LogDt <= @DeleteBeforeDt

     -- Determine if we need to handle the Collection process preventing deletes
     IF ( @RepositoryInUseFlag = 1 )
     BEGIN -- Repository in use
          IF ( @MaxEventLogIdForDt <= @MaxEventLogIdCollectedByRepos )
          BEGIN -- The records in range for the date are less than what has been
                -- collected.
               SELECT @BeforeEventLogId = @MaxEventLogIdForDt
          END
          ELSE
          BEGIN -- The records in range for the date are above what has been 
                -- collected, so we'll find out what we can delete.
               -- Get the highest id that is in the date range we want AN below
               -- what has been picked up by the collection process.
               SELECT @BeforeEventLogId = MAX(EventLogId)
               FROM   dbo.EventLog 
               WHERE  EventLogId <= @MaxEventLogIdCollectedByRepos
               AND    LogDt      <= @DeleteBeforeDt
          END
     END
     ELSE
     BEGIN -- Repository NOT in use
          SET @BeforeEventLogId = @MaxEventLogIdForDt
     END

     -- Delete the records that are in scope, keeping in mind what has or has
     -- not been collected by the collection process..
     DELETE 
     FROM   dbo.EventLog
     WHERE  EventLogId <= @BeforeEventLogId 

     SELECT @RC = @@ROWCOUNT

     SELECT @msg = 'Process Ending.  @DeleteBeforeDt in MiscDt1, '
                 + '@MaxEventLogIdForDt in MiscBigInt1, '
                 + '@MaxEventLogIdCollectedByRepos in MiscBigInt2, '
                 + '@BeforeEventLogId in MiscBigInt3, '
                 + 'Records deleted count in MiscBigInt4, '
                 + '@RepositoryInUseFlag in MiscTinyInt1.'

     EXEC dbo.InsEventLog @EventLogTypeId     = 1, -- Info
                          @LogByApp           = 'PurgeEventLog',
                          @LogText            = @msg,
                          @MiscDt1            = @DeleteBeforeDt,
                          @MiscBigInt1        = @MaxEventLogIdForDt,
                          @MiscBigInt2        = @MaxEventLogIdCollectedByRepos,
                          @MiscBigInt3        = @BeforeEventLogId,
                          @MiscBigInt4        = @RC,
                          @MiscTinyInt1       = @RepositoryInUseFlag
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Purges records out of the eventlog table after they have been held for the required period of time.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = PurgeEventLog;
GO
IF EXISTS ( SELECT * FROM sysobjects WHERE name = 'SaveCfgCtrl' AND type = 'P' AND uid = 1 )
     DROP PROCEDURE dbo.SaveCfgCtrl
GO

CREATE PROCEDURE dbo.SaveCfgCtrl
     @CfgCtrlKey            varchar(30), 
     @CfgCtrlValue          varchar(8000),
     @CfgCtrlDescription    varchar(128) = NULL, -- Optional entry
     @SuppressResultsetFlag tinyint      = 0
AS
/*
 *
 * SaveCfgCtrl
 *
 * Purpose:      To Add and update records to the CfgCtrl table.
 *
 * Inputs:       
 *
 * Assumes:      CfgCtrl table exists
 *
 * Effects:      Records are inserted or updated in CfgCtrl
 *
 * Returns:      CfgCtrlKey, CfgCtrlDescription, and CfgCtrlValue
 *
 * Calling
 * Application:  
 *
 * Note(s):      Post change values are returned for app verification of save.
 *
 *               The description, once written cannot be changed here.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 01/06/2012, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     IF ( @CfgCtrlKey IS NULL ) 
     BEGIN
          RAISERROR( 'CfgCtrlKey must be specified.', 16, 1 )
     END
     ELSE
     BEGIN -- We got a value
          IF EXISTS ( SELECT 'X' FROM dbo.CfgCtrl WHERE CfgCtrlKey = @CfgCtrlKey )
          BEGIN -- Update
               UPDATE dbo.CfgCtrl
               SET    LastModDt    = CURRENT_TIMESTAMP,
                      CfgCtrlValue = LTRIM( RTRIM( @CfgCtrlValue ) )
               FROM   dbo.CfgCtrl
               WHERE  CfgCtrlKey = @CfgCtrlKey
          END
          ELSE
          BEGIN -- Insert
               INSERT dbo.CfgCtrl
                    ( CfgCtrlKey, 
                      CfgCtrlDescription, 
                      CfgCtrlValue )
               SELECT LTRIM( RTRIM( @CfgCtrlKey ) ),
                      ISNULL( LTRIM( RTRIM( @CfgCtrlDescription ) ), 'Unspecified' ),
                      LTRIM( RTRIM( @CfgCtrlValue ) )
          END
     END

     -- Output results if allowed
     IF ( @SuppressResultsetFlag != 1 )
     BEGIN
          SELECT CfgKey         = LTRIM( RTRIM( CfgCtrlKey ) ),
                 CfgDescription = LTRIM( RTRIM( CfgCtrlDescription ) ),
                 CfgValue       = LTRIM( RTRIM( CfgCtrlValue ) )
          FROM   dbo.CfgCtrl
          WHERE  CfgCtrlKey = @CfgCtrlKey
     END
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveInstanceInfoFromWMI' AND type = 'P')
     DROP PROCEDURE dbo.SaveInstanceInfoFromWMI
GO

CREATE PROCEDURE dbo.SaveInstanceInfoFromWMI
     @PackageExecutionId bigint,
     @NoGuessingFlag     tinyint = 0
AS
/*
 *
 * SaveInstanceInfoFromWMI
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/19/2011, 1.00.0000
 *               NCL, 11/17/2011, 1.00.0001
 *               Modified for installed services handling.
 *               NCL, 12/08/2011, 1.00.0002
 *               Bug fix, "deleted" services of machines OTHER than the one
 *               it was currently working on.
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @RecId                int,
             @SrvrInstncId         int,
             @ActualInstanceName   varchar(255),
             @tempFullInstanceName varchar(255)

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Handle NULL Actual Names
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- These are instances that we were unable to connect to to determine the 
     -- machine name that it reports.  This could be because although we detected
     -- the service it was not running or perhaps it was identified on a cluster
     -- node and we could not connect to it by the name specified.  But since 
     -- we can make some assumptions we can perhaps guess, such as for a given 
     -- machine a named instance can only be used once either stand-alone or 
     -- clustered.  Hopefully these variations will be handled during the 
     -- machine inserts during cluster node determination in the instance
     -- processing.
     IF ( @NoGuessingFlag <> 1 )
     BEGIN
          UPDATE tempdb.dbo.tempDiscoverMSSQLServersList
          SET    SrvrInstncId = sim.SrvrInstncId
          FROM   dbo.MachineCluster mc INNER JOIN dbo.Machine m
                    ON mc.MemberMachineId = m.MachineId
                 INNER JOIN tempdb.dbo.tempDiscoverMSSQLServersList dsl
                    ON m.MachineName = dsl.MachineName
                 INNER JOIN dbo.SrvrInstncMachine sim
                    ON sim.MachineId = m.MachineId
                 INNER JOIN dbo.SrvrInstncMSSQL sims
                    ON sims.SrvrInstncId           = sim.SrvrInstncId
                   AND sims.SrvrInstncInstanceName = dsl.InstanceName
          WHERE  dsl.ActualFullInstanceName IS NULL
     END

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Handle Non-NULL Actual Names
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- We will now try and lookup any existing server instance ids, the ones
     -- where we find a record will be treated as aliases to the server instance
     -- where we don't will be added as new instances.

     UPDATE tempdb.dbo.tempDiscoverMSSQLServersList
     SET    SrvrInstncId = si.SrvrInstncId
     FROM   tempdb.dbo.tempDiscoverMSSQLServersList dsl INNER JOIN dbo.SrvrInstnc si
               ON dsl.ActualFullInstanceName = si.SrvrInstncFullName
     WHERE  dsl.ActualFullInstanceName IS NOT NULL

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Perform consolidated processing
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- We'll start by adding new server instances
     DECLARE NewInstance CURSOR FOR SELECT RecId
                                    FROM   tempdb.dbo.tempDiscoverMSSQLServersList
                                    WHERE  ActualFullInstanceName IS NOT NULL
                                    AND    SrvrInstncId           IS NULL

     OPEN NewInstance

     FETCH NEXT FROM NewInstance INTO @RecId

     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          SELECT @ActualInstanceName   = ActualFullInstanceName,
                 @tempFullInstanceName = FullInstanceName
          FROM   tempdb.dbo.tempDiscoverMSSQLServersList
          WHERE  RecId = @RecId

          -- Just in case something weird happens we are gonna check to be sure
          -- that the actual name hasn't already been added, there is a case
          -- were it might be possible to have more than one record line up but
          -- it is an edge case that should never occur but we'll check anyway.
          IF EXISTS ( SELECT 1 FROM dbo.SrvrInstnc WHERE SrvrInstncFullName = @ActualInstanceName )
          BEGIN -- We found it so we get the value for SrvrInstncId
               SELECT @SrvrInstncId = SrvrInstncId 
               FROM   dbo.SrvrInstnc 
               WHERE  SrvrInstncFullName = @ActualInstanceName
          END
          ELSE
          BEGIN
               EXEC dbo.InsSrvrInstnc
                         @SrvrInstncFullName = @ActualInstanceName,
                         @SrvrInstncTypeId   = 1, -- MSSQL
                         @SrvrInstncGrpId    = 1, -- Default Group
                         @SrvrInstncId       = @SrvrInstncId OUTPUT
          END

          IF ( @ActualInstanceName != @tempFullInstanceName ) 
          BEGIN -- We have a case where the actual name and reported name differ
                -- we add an alias
               INSERT dbo.SrvrInstncAlias
                    ( SrvrInstncId,
                      SrvrInstncFullName )
               SELECT @SrvrInstncId,
                      @tempFullInstanceName
          END

          FETCH NEXT FROM NewInstance INTO @RecId
     END

     CLOSE NewInstance
     DEALLOCATE NewInstance

     -- We will handle the cases where have found a SrvrInstnc Id, these should 
     -- be aliases but we will check, we insert aliases directly.
     INSERT dbo.SrvrInstncAlias
          ( SrvrInstncId,
            SrvrInstncFullName,
            DoNotUseFlag,
            LastModDt )
     SELECT SrvrInstncId,
            FullInstanceName,
            DoNotUseFlag = CASE WHEN dsl.ActualFullInstanceName IS NULL THEN 1 ELSE 0 END,
            CURRENT_TIMESTAMP
     FROM   tempdb.dbo.tempDiscoverMSSQLServersList dsl
     -- Be sure it don't exist in the server instance already
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.SrvrInstnc si
                         WHERE  si.SrvrInstncFullName = dsl.FullInstanceName )
     -- Be sure it isn't already an alias
     AND    NOT EXISTS ( SELECT 1
                         FROM   dbo.SrvrInstncAlias sia
                         WHERE  sia.SrvrInstncFullName = dsl.FullInstanceName )
     AND    dsl.SrvrInstncId IS NOT NULL

     -- Last we will handle the records that are unresolved, we will store them
     -- for manual resolution at a later time.
     INSERT dbo.UnresolvedMSSQLInstnc
          ( PackageExecutionId,
            FullInstanceName,
            MachineName,
            InstanceName,
            LoginName,
            ServiceRunningFlag,
            IsClusteredFlag,
            ErrorDesc )
     SELECT PackageExecutionId,
            FullInstanceName,
            MachineName,
            InstanceName,
            LoginName,
            ServiceRunningFlag,
            IsClusteredFlag,
            ErrorDesc
     FROM   tempdb.dbo.tempDiscoverMSSQLServersList dsl
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.UnresolvedMSSQLInstnc u
                         WHERE  u.FullInstanceName = dsl.FullInstanceName )
     AND    dsl.ActualFullInstanceName IS NULL
     AND    dsl.SrvrInstncId           IS NULL

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Perform MS Installed Service Processing.
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- Condition IsClusteredFlag
     UPDATE tempdb.dbo.tempDiscoverMSInstalledServersList
     SET    IsClusteredFlag = CASE WHEN IsClusteredFlag = 1 THEN 1 ELSE 0 END
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList
     WHERE  IsClusteredFlag IS NULL
     OR     IsClusteredFlag NOT IN ( 0, 1 )

     -- Get Machine Ids for machines.
     UPDATE tempdb.dbo.tempDiscoverMSInstalledServersList
     SET    MachineId = m.MachineId
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl INNER JOIN dbo.Machine m
               ON sl.MachineName = m.MachineName

     -- Get Server Instance Id for SQL Servers
     UPDATE tempdb.dbo.tempDiscoverMSInstalledServersList
     SET    SrvrInstncId = si.SrvrInstncId
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl INNER JOIN dbo.SrvrInstnc si
               ON sl.FullInstanceName = si.SrvrInstncFullName
     WHERE  si.SrvrInstncTypeId = 1 -- MSSQL
     AND    sl.ServiceTypeId    = 1 -- SQL Server

     -- Get Server Instance Id for SQL Servers By Alias
     UPDATE tempdb.dbo.tempDiscoverMSInstalledServersList
     SET    SrvrInstncId = sia.SrvrInstncId
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl INNER JOIN dbo.SrvrInstncAlias sia
               ON sl.FullInstanceName = sia.SrvrInstncFullName
            INNER JOIN dbo.SrvrInstnc si
               ON sia.SrvrInstncId = si.SrvrInstncId
     WHERE  si.SrvrInstncTypeId = 1 -- MSSQL
     AND    sl.ServiceTypeId    = 1 -- SQL Server
     AND    sia.DoNotUseFlag    = 0

     -- Play Paranoid for a minute, we make sure that the correlations have been
     -- made for MSSQL Servers.
     INSERT dbo.SrvrInstncMSSQL
          ( SrvrInstncId,
            SrvrInstncMachineName,
            SrvrInstncInstanceName )
     SELECT si.SrvrInstncId,
            dbo.GetMachineNameFromMSSQLFullInstanceName( si.SrvrInstncFullName ),
            dbo.GetInstanceNameFromMSSQLFullInstanceName( si.SrvrInstncFullName )
     FROM   dbo.SrvrInstnc si
     WHERE  SrvrInstncTypeId = 1 -- MSSQL
     AND    NOT EXISTS ( SELECT 1
                         FROM   dbo.SrvrInstncMSSQL sim
                         WHERE  sim.SrvrInstncId = si.SrvrInstncId )

     -- Get Server Instance Id for SQL Servers when we are referring to the base
     -- machine name with or without an instance and not the virtual name.  This
     -- only happens for clustered machines.
     UPDATE tempdb.dbo.tempDiscoverMSInstalledServersList
     SET    SrvrInstncId = si.SrvrInstncId
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl INNER JOIN dbo.SrvrInstncMachine sim
               ON sl.MachineId = sim.MachineId 
            INNER JOIN dbo.SrvrInstncMSSQL simm
               ON sim.SrvrInstncId = simm.SrvrInstncId
              AND simm.SrvrInstncInstanceName = sl.InstanceName
            INNER JOIN dbo.SrvrInstnc si
               ON sim.SrvrInstncId = si.SrvrInstncId
     WHERE  si.SrvrInstncTypeId = 1 -- MSSQL
     AND    sl.ServiceTypeId    = 1 -- SQL Server
     AND    sl.IsClusteredFlag  = 1

     -- Handled related services
     UPDATE sl2
     SET    RelatedToSrvrInstncId = sl1.SrvrInstncId
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl1 INNER JOIN tempdb.dbo.tempDiscoverMSInstalledServersList sl2
               ON sl1.MachineId     = sl2.MachineId
              AND sl1.InstanceName  = sl2.InstanceName
              AND sl1.ServiceTypeId = 1 
              AND sl2.ServiceTypeId IN ( 2, 5, 9 ) -- Agent, SSAS, Full-Text

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Write MS Installed Services
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- Handle Insert
     INSERT dbo.MachineMSInstalledComponents
          ( MachineId,
            PackageExecutionId,
            ServiceName,
            InstanceName,
            InstalledComponentName,
            IsClusteredFlag,
            SrvrInstncId,
            InstalledComponentDeletedFlag,
            LastModDt )
     SELECT sl.MachineId,
            sl.PackageExecutionId,
            sl.ServiceName,
            sl.InstanceName,
            sl.ServiceType,
            sl.IsClusteredFlag,
            sl.SrvrInstncId,
            0, -- InstalledComponentDeletedFlag
            CURRENT_TIMESTAMP -- LastModDt
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.MachineMSInstalledComponents m
                         WHERE  sl.MachineId   = m.MachineId 
                         AND    sl.ServiceName = m.ServiceName )
     AND    sl.MachineId IS NOT NULL 

     -- Handle Deletes
     UPDATE dbo.MachineMSInstalledComponents
     SET    InstalledComponentDeletedFlag = 1
     FROM   dbo.MachineMSInstalledComponents m
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl
                         WHERE  sl.MachineId   = m.MachineId 
                         AND    sl.ServiceName = m.ServiceName )
     -- Only "delete" those services on the current machine.
     AND    EXISTS ( SELECT 1
                     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl
                     WHERE  sl.MachineId   = m.MachineId )

     -- Handle Re-Installed/Updated Services, MachineId, InstanceName and 
     -- ServiceName cannot be changed, PEI and LastModDt are not checked
     UPDATE dbo.MachineMSInstalledComponents
     SET    PackageExecutionId            = sl.PackageExecutionId,
            InstalledComponentName        = sl.ServiceType,
            IsClusteredFlag               = sl.IsClusteredFlag,
            SrvrInstncId                  = sl.SrvrInstncId,
            RelatedToSrvrInstncId         = sl.RelatedToSrvrInstncId,
            InstalledComponentDeletedFlag = 0,
            LastModDt                     = CURRENT_TIMESTAMP
     FROM   tempdb.dbo.tempDiscoverMSInstalledServersList sl INNER JOIN dbo.MachineMSInstalledComponents m
               ON sl.MachineId   = m.MachineId 
              AND sl.ServiceName = m.ServiceName
     WHERE  m.InstalledComponentDeletedFlag = 1
     OR   ( m.InstalledComponentDeletedFlag = 0
        AND ( m.InstalledComponentName != sl.ServiceType
           OR m.IsClusteredFlag        != sl.IsClusteredFlag
           OR ( m.SrvrInstncId                       != sl.SrvrInstncId
           OR ( m.SrvrInstncId          IS NOT NULL AND sl.SrvrInstncId          IS     NULL
             OR m.SrvrInstncId          IS     NULL AND sl.SrvrInstncId          IS NOT NULL )
              )
           OR ( m.RelatedToSrvrInstncId              != sl.RelatedToSrvrInstncId
           OR ( m.RelatedToSrvrInstncId IS NOT NULL AND sl.RelatedToSrvrInstncId IS     NULL
             OR m.RelatedToSrvrInstncId IS     NULL AND sl.RelatedToSrvrInstncId IS NOT NULL )
             )
            )
          )

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- End
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'We take the list and try to make relationships to the existing server instances, it will also add server instances where we can clearly identify them.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveInstanceInfoFromWMI;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMachine' AND type = 'P')
     DROP PROCEDURE dbo.SaveMachine
GO

CREATE PROCEDURE dbo.SaveMachine
     @PackageExecutionId          bigint,
     @ComputerNamePhysicalNetBIOS varchar(128) = NULL,
     @MachineName                 varchar(128) = NULL,
     @FQMachineName               varchar(255) = NULL,
     @PhysicalCPUCount            int          = NULL,
     @PhysicalCPUCoreCount        int          = NULL,
     @LogicalCPUCoreCount         int          = NULL,
     @MaxCPUSpeedMHz              int          = NULL,
     @OSVersion                   VARCHAR(30)  = NULL,
     @OSLevel                     varchar(30)  = NULL,
     @OSArchitecture              varchar(10)  = NULL,
     @OSEdition                   varchar(128) = NULL,
     @TotalMachineMemoryMB        int          = NULL,
     @RSVDMachineMemoryMB         int          = NULL,
     @ClusterVirtualNameFlag      tinyint      = NULL,
     @SuppressResultSetFlag       tinyint      = 0,
     @MachineId                   int          = NULL OUTPUT
AS
/*
 *
 * SaveSrvrMachine
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @CalcMachineName varchar(128)

     SET @MachineId = NULL

     -- Determine Calculated machine name by evaluating @ComputerNamePhysicalNetBIOS, 
     -- and then @MachineName in that order
     SELECT @CalcMachineName = COALESCE(@ComputerNamePhysicalNetBIOS, @MachineName )

     IF ( @CalcMachineName IS NULL )
     BEGIN -- We don't have a name so we are done.  We will take no action.
          RETURN 
     END

     -- If we didn't get an FQ name we make FQ = name
     SELECT @FQMachineName = ISNULL( @FQMachineName, @CalcMachineName )

     -- Calculate Reserved Memory if needed
     IF ( @RSVDMachineMemoryMB IS NULL )
     BEGIN
          SELECT @RSVDMachineMemoryMB = @RSVDMachineMemoryMB
          FROM   dbo.Machine
          WHERE  MachineName = @CalcMachineName

          -- If its still null we'll try and calc it..
          SELECT @RSVDMachineMemoryMB = COALESCE( @RSVDMachineMemoryMB, dbo.GetRSVDMemoryMBByTotalMemoryMB( @TotalMachineMemoryMB ) )
     END

     -- Check to see if the machine is stored
     IF EXISTS ( SELECT 'X'
                 FROM   dbo.Machine 
                 WHERE  MachineName = @CalcMachineName )
     BEGIN -- Existing record
          UPDATE dbo.Machine
          SET    PackageExecutionId     = @PackageExecutionId,
                 FQMachineName          = CASE WHEN @FQMachineName IS NULL AND FQMachineName IS NOT NULL
                                               THEN FQMachineName
                                               WHEN @FQMachineName =''
                                               THEN NULL
                                               ELSE @FQMachineName
                                          END,
                 PhysicalCPUCount       = CASE WHEN @PhysicalCPUCount IS NULL AND PhysicalCPUCount IS NOT NULL
                                               THEN PhysicalCPUCount
                                               WHEN @PhysicalCPUCount = 0
                                               THEN NULL
                                               ELSE @PhysicalCPUCount
                                          END,
                 PhysicalCPUCoreCount   = CASE WHEN @PhysicalCPUCoreCount IS NULL AND PhysicalCPUCoreCount IS NOT NULL
                                               THEN PhysicalCPUCoreCount
                                               WHEN @PhysicalCPUCoreCount = 0
                                               THEN NULL
                                               ELSE @PhysicalCPUCoreCount
                                          END,
                 LogicalCPUCoreCount    = CASE WHEN @LogicalCPUCoreCount IS NULL AND LogicalCPUCoreCount IS NOT NULL
                                               THEN LogicalCPUCoreCount
                                               WHEN @LogicalCPUCoreCount = 0
                                               THEN NULL
                                               ELSE @LogicalCPUCoreCount
                                          END,
                 MaxCPUSpeedMHz         = CASE WHEN @MaxCPUSpeedMHz IS NULL AND MaxCPUSpeedMHz IS NOT NULL
                                               THEN MaxCPUSpeedMHz
                                               WHEN @MaxCPUSpeedMHz = 0
                                               THEN NULL
                                               ELSE @MaxCPUSpeedMHz
                                          END,
                 OSVersion              = CASE WHEN @OSVersion IS NULL AND OSVersion IS NOT NULL
                                               THEN OSVersion
                                               ELSE @OSVersion
                                          END,
                 OSLevel                = CASE WHEN @OSLevel IS NULL AND OSLevel IS NOT NULL
                                               THEN OSLevel
                                               ELSE @OSLevel
                                          END,
                 OSArchitecture         = CASE WHEN @OSArchitecture IS NULL AND OSArchitecture IS NOT NULL
                                               THEN OSArchitecture
                                               ELSE @OSArchitecture
                                          END,
                 OSEdition              = CASE WHEN @OSEdition IS NULL AND OSEdition IS NOT NULL
                                               THEN OSEdition
                                               ELSE @OSEdition
                                          END,
                 TotalMachineMemoryMB   = CASE WHEN @TotalMachineMemoryMB IS NULL AND TotalMachineMemoryMB IS NOT NULL
                                               THEN TotalMachineMemoryMB
                                               WHEN @TotalMachineMemoryMB = 0
                                               THEN NULL
                                               ELSE @TotalMachineMemoryMB
                                          END,
                 RSVDMachineMemoryMB    = CASE WHEN @RSVDMachineMemoryMB IS NULL AND RSVDMachineMemoryMB IS NOT NULL
                                               THEN RSVDMachineMemoryMB
                                               WHEN @RSVDMachineMemoryMB IS NULL AND RSVDMachineMemoryMB IS NULL
                                               THEN dbo.GetRSVDMemoryMBByTotalMemoryMB( @TotalMachineMemoryMB )
                                               WHEN @RSVDMachineMemoryMB = 0
                                               THEN dbo.GetRSVDMemoryMBByTotalMemoryMB( @TotalMachineMemoryMB )
                                               ELSE @RSVDMachineMemoryMB
                                          END,
                 ClusterVirtualNameFlag = CASE WHEN @ClusterVirtualNameFlag IS NULL AND ClusterVirtualNameFlag IS NOT NULL
                                               THEN ClusterVirtualNameFlag
                                               ELSE @ClusterVirtualNameFlag
                                          END,
                 LastModDt              = CURRENT_TIMESTAMP
          FROM   dbo.Machine 
          WHERE  MachineName = @CalcMachineName
          --AND    ( 1=0
          AND    ( ISNULL( PhysicalCPUCount,       -1 ) != ISNULL( @PhysicalCPUCount,       -1 )
                OR ISNULL( PhysicalCPUCoreCount,   -1 ) != ISNULL( @PhysicalCPUCoreCount,   -1 )
                OR ISNULL( LogicalCPUCoreCount,    -1 ) != ISNULL( @LogicalCPUCoreCount,    -1 )
                OR ISNULL( MaxCPUSpeedMHz,         -1 ) != ISNULL( @MaxCPUSpeedMHz,         -1 )
                OR ISNULL( TotalMachineMemoryMB,   -1 ) != ISNULL( @TotalMachineMemoryMB,   -1 )
                OR ISNULL( RSVDMachineMemoryMB,    -1 ) != ISNULL( @RSVDMachineMemoryMB,    -1 )
               -- We only need to test ineqity for non-null fields.
                OR ( ClusterVirtualNameFlag      != @ClusterVirtualNameFlag )
               -- We are not testing for the case where we have a value and would set the value to NULL
                OR ( FQMachineName  IS     NULL AND @FQMachineName IS NOT NULL 
               -- OR FQMachineName  IS NOT NULL AND @FQMachineName IS     NULL 
                  OR FQMachineName               != @FQMachineName )
                OR ( OSVersion      IS     NULL AND @OSVersion      IS NOT NULL 
               -- OR OSVersion      IS NOT NULL AND @OSVersion      IS     NULL 
                  OR OSVersion                   != @OSVersion )
                OR ( OSLevel        IS     NULL AND @OSLevel        IS NOT NULL 
               -- OR OSLevel        IS NOT NULL AND @OSLevel        IS     NULL 
                  OR OSLevel                     != @OSLevel )
                OR ( OSArchitecture IS     NULL AND @OSArchitecture IS NOT NULL 
               -- OR OSArchitecture IS NOT NULL AND @OSArchitecture IS     NULL 
                  OR OSArchitecture              != @OSArchitecture )
                OR ( OSEdition      IS     NULL AND @OSEdition      IS NOT NULL 
               -- OR OSEdition      IS NOT NULL AND @OSEdition      IS     NULL 
                  OR OSEdition                   != @OSEdition )
                 ) -- Closing Paren

          SELECT @MachineId = MachineId
          FROM   dbo.Machine 
          WHERE  MachineName = @CalcMachineName 
     END
     ELSE
     BEGIN -- Do Insert
          INSERT dbo.Machine 
               ( PackageExecutionId,
                 EnabledFlag,
                 MachineName,
                 FQMachineName,
                 PhysicalCPUCount,
                 PhysicalCPUCoreCount,
                 LogicalCPUCoreCount,
                 MaxCPUSpeedMHz,
                 OSVersion,
                 OSLevel,
                 OSArchitecture,
                 OSEdition,
                 TotalMachineMemoryMB,
                 RSVDMachineMemoryMB )
          SELECT @PackageExecutionId,
                 1, -- EnabledFlag
                 @CalcMachineName,
                 @FQMachineName,
                 @PhysicalCPUCount,
                 @PhysicalCPUCoreCount,
                 @LogicalCPUCoreCount,
                 @MaxCPUSpeedMHz,
                 @OSVersion,
                 @OSLevel,
                 @OSArchitecture,
                 @OSEdition,
                 @TotalMachineMemoryMB,
                 @RSVDMachineMemoryMB

          SELECT @MachineId = SCOPE_IDENTITY()
     END

     IF ( @SuppressResultSetFlag != 1 ) 
     BEGIN
          SELECT MachineId = @MachineId 
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Saves a machine record if is is not already existing in the list, this represents a physical (or virtual) machine and not necessarily a database instance.  This sproc is called by SaveSrvrMachineSrvrInstncMachine.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveMachine;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMachineDriveVolume' AND type = 'P')
     DROP PROCEDURE dbo.SaveMachineDriveVolume
GO

CREATE PROCEDURE dbo.SaveMachineDriveVolume
     @MachineId                int,
     @PackageExecutionId       bigint,
     @VolumeDeviceId           varchar(128),
     @VolumeMountPoint         varchar(255),
     @VolumeBlockSize          int,
     @VolumeCapacity           bigint,
     @VolumeCompressedFlag     tinyint,
     @VolumeDriveTypeDesc      varchar(30),
     @VolumeFileSystemType     varchar(6),
     @VolumeLabel              varchar(32),
     @VolumeName               varchar(128),
     @VolumeSerialNumber       bigint,
     @ClusterSharedVolumeFlag  tinyint = 0,
     @PackageExecutionIdStr    varchar(30)   = NULL,
     @VolumeDeletedFlag        tinyint       = 0,
     @MachineDriveVolumeId     int           = NULL OUTPUT
AS
/*
 *
 * SaveMachineDriveVolume
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/30/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @VolumeIdForSrv int,
             @StartDt        datetime,
             @RC             int,
             @NOW            datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Handle case of PackageExecutionId
     IF ( @PackageExecutionId IS NULL AND @PackageExecutionIdStr IS NOT NULL )
     BEGIN -- Id value ALWAYS takes precedence
          SELECT @PackageExecutionId = CONVERT( bigint, @PackageExecutionIdStr )
     END
     ELSE 
     BEGIN -- All other cases we set the string to match the id
          SELECT @PackageExecutionIdStr = CONVERT( varchar(30), @PackageExecutionId )
     END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 1
                     FROM   dbo.MachineDriveVolume
                     WHERE  MachineId      = @MachineId 
                     AND    VolumeDeviceId = @VolumeDeviceId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          -- Get the Id 
          SELECT @VolumeIdForSrv = ISNULL(MAX(MachineDriveVolumeId),0) + 1
          FROM   dbo.MachineDriveVolume
          WHERE  MachineId = @MachineId 

          INSERT dbo.MachineDriveVolume
               ( MachineId,
                 MachineDriveVolumeId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 PackageExecutionId,
                 VolumeDeletedFlag,
                 VolumeDeviceId,
                 VolumeMountPoint,
                 VolumeBlockSize,
                 VolumeCapacity,
                 VolumeCompressedFlag,
                 VolumeDriveTypeDesc,
                 VolumeFileSystemType,
                 VolumeLabel,
                 VolumeName,
                 VolumeSerialNumber,
                 ClusterSharedVolumeFlag )
          SELECT @MachineId,
                 @VolumeIdForSrv,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @PackageExecutionId,
                 0, -- VolumeDeletedFlag
                 @VolumeDeviceId,
                 @VolumeMountPoint,
                 @VolumeBlockSize,
                 @VolumeCapacity,
                 @VolumeCompressedFlag,
                 @VolumeDriveTypeDesc,
                 @VolumeFileSystemType,
                 @VolumeLabel,
                 @VolumeName,
                 @VolumeSerialNumber,
                 @ClusterSharedVolumeFlag
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the Drive Vol Id 
          SELECT @VolumeIdForSrv = MachineDriveVolumeId 
          FROM   dbo.MachineDriveVolume
          WHERE  MachineId      = @MachineId 
          AND    VolumeDeviceId = @VolumeDeviceId

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.MachineDriveVolume
          WHERE  MachineId            = @MachineId 
          AND    MachineDriveVolumeId = @VolumeIdForSrv
          AND    CurrentRecordFlag    = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.MachineDriveVolume 
          SET    EndDt              = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag  = 0
          WHERE  MachineId            = @MachineId 
          AND    MachineDriveVolumeId = @VolumeIdForSrv
          AND    CurrentRecordFlag    = 1

          IF ( @VolumeDeletedFlag = 0 )
          BEGIN -- Do regular insert
               INSERT dbo.MachineDriveVolume
                    ( MachineId,
                      MachineDriveVolumeId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      VolumeDeletedFlag,
                      VolumeDeviceId,
                      VolumeMountPoint,
                      VolumeBlockSize,
                      VolumeCapacity,
                      VolumeCompressedFlag,
                      VolumeDriveTypeDesc,
                      VolumeFileSystemType,
                      VolumeLabel,
                      VolumeName,
                      VolumeSerialNumber,
                      ClusterSharedVolumeFlag )
               SELECT @MachineId,
                      @VolumeIdForSrv,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      0, -- VolumeDeletedFlag
                      @VolumeDeviceId,
                      @VolumeMountPoint,
                      @VolumeBlockSize,
                      @VolumeCapacity,
                      @VolumeCompressedFlag,
                      @VolumeDriveTypeDesc,
                      @VolumeFileSystemType,
                      @VolumeLabel,
                      @VolumeName,
                      @VolumeSerialNumber,
                      @ClusterSharedVolumeFlag
               FROM   dbo.MachineDriveVolume
               WHERE  MachineId            = @MachineId 
               AND    MachineDriveVolumeId = @VolumeIdForSrv
               --AND    PackageExecutionId   = @PEI
               AND    StartDt              = @StartDt
               -- Decide if there will be an insert
               AND  ( VolumeDeletedFlag = 1
                      --1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR @VolumeMountPoint        != VolumeMountPoint
                   OR @VolumeBlockSize         != VolumeBlockSize
                   OR @VolumeCapacity          != VolumeCapacity
                   OR @VolumeCompressedFlag    != VolumeCompressedFlag
                   OR @VolumeDriveTypeDesc     != VolumeDriveTypeDesc
                   OR @VolumeLabel             != VolumeLabel
                   OR @VolumeName              != VolumeName
                   OR @VolumeSerialNumber      != VolumeSerialNumber
                   OR @ClusterSharedVolumeFlag != ClusterSharedVolumeFlag
                   -- Handle the three NULLable fields
                   OR ( @VolumeMountPoint     IS NULL     AND VolumeMountPoint     IS NOT NULL )
                   OR ( @VolumeMountPoint     IS NOT NULL AND VolumeMountPoint     IS NULL )
                   OR ( @VolumeBlockSize      IS NULL     AND VolumeBlockSize      IS NOT NULL )
                   OR ( @VolumeBlockSize      IS NOT NULL AND VolumeBlockSize      IS NULL )
                   OR ( @VolumeCapacity       IS NULL     AND VolumeCapacity       IS NOT NULL )
                   OR ( @VolumeCapacity       IS NOT NULL AND VolumeCapacity       IS NULL )
                   OR ( @VolumeCompressedFlag IS NULL     AND VolumeCompressedFlag IS NOT NULL )
                   OR ( @VolumeCompressedFlag IS NOT NULL AND VolumeCompressedFlag IS NULL )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               -- See if it is already deleted, if so, break!
               IF EXISTS ( SELECT 1 
                           FROM   dbo.MachineDriveVolume 
                           WHERE  MachineId            = @MachineId
                           AND    MachineDriveVolumeId = @VolumeIdForSrv
                           AND    StartDt              = @StartDt
                           AND    VolumeDeletedFlag    = 0 )
               BEGIN -- Not already deleted.
                    INSERT dbo.MachineDriveVolume
                         ( MachineId,
                           MachineDriveVolumeId,
                           StartDt,
                           EndDt,
                           CurrentRecordFlag,
                           PackageExecutionId,
                           VolumeDeletedFlag,
                           VolumeDeviceId,
                           VolumeMountPoint,
                           VolumeBlockSize,
                           VolumeCapacity,
                           VolumeCompressedFlag,
                           VolumeDriveTypeDesc,
                           VolumeFileSystemType,
                           VolumeLabel,
                           VolumeName,
                           VolumeSerialNumber,
                           ClusterSharedVolumeFlag )
                    SELECT MachineId,
                           MachineDriveVolumeId,
                           @NOW, -- StartDt
                           '12/31/9999', -- EndDt
                           1, -- CurrentRecordFlag
                           @PackageExecutionId,
                           1, -- VolumeDeletedFlag
                           VolumeDeviceId,
                           VolumeMountPoint,
                           VolumeBlockSize,
                           VolumeCapacity,
                           VolumeCompressedFlag,
                           VolumeDriveTypeDesc,
                           VolumeFileSystemType,
                           VolumeLabel,
                           VolumeName,
                           VolumeSerialNumber,
                           ClusterSharedVolumeFlag
                    FROM   dbo.MachineDriveVolume
                    WHERE  MachineId            = @MachineId
                    AND    MachineDriveVolumeId = @VolumeIdForSrv
                    --AND    PackageExecutionId   = @PEI
                    AND    StartDt              = @StartDt

                    SELECT @RC = @@ROWCOUNT 
               END
          END

          SET @MachineDriveVolumeId = @VolumeIdForSrv

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMachineEnvVar' AND type = 'P')
     DROP PROCEDURE dbo.SaveMachineEnvVar
GO

CREATE PROCEDURE dbo.SaveMachineEnvVar
     @MachineId                int,
     @PackageExecutionId       bigint,
     @VarName                  varchar(100),
     @VarUser                  varchar(100),
     @VarVal                   varchar(7680),
     @PackageExecutionIdStr    varchar(30)   = NULL,
     @VarDeletedFlag           tinyint       = 0
AS
/*
 *
 * SaveMachineEnvVar
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 9/29/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @EnvIdForSrv int,
             @StartDt     datetime,
             @RC          int,
             @NOW         datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Handle case of PackageExecutionId
     IF ( @PackageExecutionId IS NULL AND @PackageExecutionIdStr IS NOT NULL )
     BEGIN -- Id value ALWAYS takes precedence
          SELECT @PackageExecutionId = CONVERT( bigint, @PackageExecutionIdStr )
     END
     ELSE 
     BEGIN -- All other cases we set the string to match the id
          SELECT @PackageExecutionIdStr = CONVERT( varchar(30), @PackageExecutionId )
     END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.MachineEnvVar
                     WHERE  MachineId  = @MachineId 
                     AND    VarName    = @VarName
                     AND    VarUser    = @VarUser )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          -- Get the env Id 
          SELECT @EnvIdForSrv = ISNULL(MAX(MachineEnvVarId),0) + 1
          FROM   dbo.MachineEnvVar
          WHERE  MachineId  = @MachineId 

          INSERT dbo.MachineEnvVar
               ( MachineId,
                 MachineEnvVarId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 PackageExecutionId,
                 VarDeletedFlag,
                 VarName,
                 VarUser,
                 VarVal )
          SELECT @MachineId,
                 @EnvIdForSrv,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @PackageExecutionId,
                 0, -- VarDeletedFlag
                 @VarName,
                 @VarUser,
                 @VarVal
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the env Id 
          SELECT @EnvIdForSrv = MachineEnvVarId 
          FROM   dbo.MachineEnvVar
          WHERE  MachineId = @MachineId 
          AND    VarName   = @VarName
          AND    VarUser   = @VarUser

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.MachineEnvVar
          WHERE  MachineId          = @MachineId 
          AND    MachineEnvVarId    = @EnvIdForSrv
          AND    CurrentRecordFlag  = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.MachineEnvVar 
          SET    EndDt              = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag  = 0
          WHERE  MachineId         = @MachineId 
          AND    MachineEnvVarId   = @EnvIdForSrv
          AND    CurrentRecordFlag = 1

          IF ( @VarDeletedFlag = 0 )
          BEGIN -- Do regular insert
               INSERT dbo.MachineEnvVar
                    ( MachineId,
                      MachineEnvVarId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      VarDeletedFlag,
                      VarName,
                      VarUser,
                      VarVal )
               SELECT @MachineId,
                      @EnvIdForSrv,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      0, -- VarDeletedFlag
                      @VarName,
                      @VarUser,
                      @VarVal
               FROM   dbo.MachineEnvVar
               WHERE  MachineId          = @MachineId 
               AND    MachineEnvVarId    = @EnvIdForSrv
               --AND    PackageExecutionId = @PEI
               AND    StartDt            = @StartDt
               -- Decide if there will be an insert
               AND  ( VarDeletedFlag = 1
                      --1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR ( @VarName                 != VarName )
                   OR ( @VarUser                 != VarUser )
                   OR (   ( @VarVal != VarVal ) 
                       OR ( @VarVal IS NULL     AND VarVal IS NOT NULL )
                       OR ( @VarVal IS NOT NULL AND VarVal IS NULL )
                      )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               -- See if it is already deleted, if so, break!
               IF EXISTS ( SELECT 1 
                           FROM   dbo.MachineEnvVar
                           WHERE  MachineId       = @MachineId
                           AND    MachineEnvVarId = @EnvIdForSrv
                           AND    StartDt         = @StartDt
                           AND    VarDeletedFlag  = 0 )
               BEGIN -- Not already deleted.
                    INSERT dbo.MachineEnvVar
                         ( MachineId,
                           MachineEnvVarId,
                           StartDt,
                           EndDt,
                           CurrentRecordFlag,
                           PackageExecutionId,
                           VarDeletedFlag,
                           VarName,
                           VarUser,
                           VarVal )
                    SELECT MachineId,
                           MachineEnvVarId,
                           @NOW, -- StartDt
                           '12/31/9999', -- EndDt
                           1, -- CurrentRecordFlag
                           @PackageExecutionId,
                           1, -- VarDeletedFlag
                           VarName,
                           VarUser,
                           VarVal
                    FROM   dbo.MachineEnvVar
                    WHERE  MachineId          = @MachineId
                    AND    MachineEnvVarId    = @EnvIdForSrv
                    --AND    PackageExecutionId = @PEI
                    AND    StartDt            = @StartDt

                    SELECT @RC = @@ROWCOUNT 
               END
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMachineInfoFromWMI' AND type = 'P')
     DROP PROCEDURE dbo.SaveMachineInfoFromWMI
GO

CREATE PROCEDURE dbo.SaveMachineInfoFromWMI
     @PackageExecutionId bigint
AS
/*
 *
 * SaveMachineInfoFromWMI
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      We perform a lot of work here, this is due to the extreme
 *               efficiencies that we can get by copying the data down to temp
 *               tables then processing it here.  The SSIS package logic 
 *               required to perform the same operations was far too complex
 *               and hard to maintain.  Much of the WMI data has to be joined
 *               to other WMI data to get a final result.  The logic for the 
 *               "delete" operations was particularly tricky and inefficient.
 *               We collect up data then process it en mass.
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/10/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Build working tables
     DECLARE @MissingNodes    TABLE ( MachineId int NOT NULL, MachineName varchar(255) NOT NULL )
     DECLARE @MissingClusters TABLE ( MachineId int NOT NULL, MachineName varchar(255) NOT NULL )

     DECLARE @MachineInfo TABLE (
               [RecId] int NOT NULL IDENTITY(1,1) PRIMARY KEY,
               [MachineName] [varchar](128) NOT NULL,
               [ClusterVirtualNameFlag] [tinyint] NOT NULL,
               [PackageExecutionId] [bigint] NOT NULL,
               [OSEdition] [varchar](128) NULL,
               [OSLevel] [varchar](30) NULL,
               [OSArchitecture] [varchar](10) NULL,
               [OSVersion] [varchar](30) NULL,
               [MaxClockSpeed] [int] NULL,
               [PhysicalCPUCount] [int] NULL,
               [PhysicalCPUCoreCount] [int] NULL,
               [LogicalCPUCount] [int] NULL,
               [TotalMachineMemoryMB] [int] NULL )

     DECLARE @ClusterVolumeWithMountPoint TABLE (
               [RecId] int NOT NULL IDENTITY(1,1) PRIMARY KEY,
	          [MachineId] [int] NOT NULL,
	          [MachineName] [varchar](128) NOT NULL,
	          [ClusterVirtualNameFlag] [tinyint] NOT NULL,
	          [PackageExecutionId] [bigint] NOT NULL,
	          [DiskId] [varchar](128) NOT NULL,
	          [ClusterDiskName] [varchar](128) NOT NULL,
	          [DiskPartitionPath] [varchar](255) NOT NULL,
	          [VolumeGUID] [varchar](38) NOT NULL,
	          [VolumeLabel] [varchar](128) NOT NULL,
	          [SerialNumber] [bigint] NOT NULL )

     DECLARE @VolumeWithMountPoint TABLE (
               [RecId] int NOT NULL IDENTITY(1,1) PRIMARY KEY,
	          [MachineId] [int] NOT NULL,
	          [MachineName] [varchar](128) NOT NULL,
	          [ClusterVirtualNameFlag] [tinyint] NOT NULL,
	          [PackageExecutionId] [bigint] NOT NULL,
	          [DeviceID] [varchar](128) NOT NULL,
	          [Name] [varchar](128) NULL,
	          [Label] [varchar](32) NULL,
	          [BlockSize] [int] NULL,
	          [Capacity] [bigint] NULL,
	          [FreeSpace] [bigint] NULL,
	          [CompressedFlag] [int] NULL,
	          [DriveTypeDesc] [varchar](30) NULL,
	          [SerialNumber] [bigint] NULL,
	          [FileSystem] [varchar](6) NULL,
	          [MountPoint] [varchar](128) NULL )

     DECLARE @EnvVar TABLE (
               [RecId] int NOT NULL IDENTITY(1,1) PRIMARY KEY,
	          [MachineId] [int] NOT NULL,
	          [MachineName] [varchar](128) NOT NULL,
	          [ClusterVirtualNameFlag] [tinyint] NOT NULL,
	          [PackageExecutionId] [bigint] NOT NULL,
	          [VarName] [varchar](100) NOT NULL,
	          [VarUser] [varchar](128) NOT NULL,
	          [VarValue] [varchar](8000) NULL )

     DECLARE @RV                   int,
             @RecId                int,
             @MachineName          varchar(128),
             @ClusterFlag          tinyint,
             @MachineId            int,
             @MachineDriveVolumeId int,
             @VolumeDeviceId       varchar(128),
             @VolumeMountPoint     varchar(255),
             @VolumeBlockSize      int,
             @VolumeCapacity       bigint,
             @VolumeFreeSpace      bigint,
             @VolumeCompressedFlag tinyint,
             @VolumeDriveTypeDesc  varchar(30),
             @VolumeFileSystemType varchar(6),
             @VolumeLabel          varchar(32),
             @VolumeName           varchar(128),
             @VolumeSerialNumber   bigint,
             @VarName              varchar(100),
             @VarUser              varchar(128),
             @VarValue             varchar(8000),
             @PhysicalCPUCount     int,
             @PhysicalCPUCoreCount int,
             @LogicalCPUCoreCount  int,
             @MaxCPUSpeedMHz       int,
             @OSVersion            varchar(30),
             @OSLevel              varchar(30),
             @OSArchitecture       varchar(10),
             @OSEdition            varchar(128),
             @TotalMachineMemoryMB int

     SET @RV = 0 -- We explicitly do this instead of setting it when we declare
                 -- for maximum compatibility.

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Machines
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- The question arose why don't we capture new machines from the SaveMachine
     -- process, the reason is that to get into that list you already have to 
     -- have existed in the Machine table.  There are 3 ways to get records into
     -- that table, the Server Info process can detect other machines, typically
     -- cluster nodes that are available to a SQL Instance, the cluster process
     -- here can detect nodes that are part of a cluster but may or may not be 
     -- involved with SQL for one or any node, and manually using the Save sproc.
     -- Given this, this process will only return machines that were detected
     -- here that were part of a clustere but not already added by the Server
     -- Info process.  

     -- Fill working table
     INSERT @MachineInfo
          ( MachineName,
            ClusterVirtualNameFlag,
            PackageExecutionId,
            OSEdition,
            OSLevel,
            OSArchitecture,
            OSVersion,
            MaxClockSpeed,
            PhysicalCPUCount,
            PhysicalCPUCoreCount,
            LogicalCPUCount,
            TotalMachineMemoryMB )
     SELECT oi.MachineName,
            ClusterVirtualNameFlag = 0,
            oi.PackageExecutionId,
            OSEdition              = oi.Caption,
            OSLevel                = oi.CSDVersion,
            OSArchitecture         = oi.OSArchitecture,
            OSVersion              = oi.Version,
            MaxClockSpeed          = ccci.MaxClockSpeed,
            PhysicalCPUCount       = cci.NumberOfProcessors,
            PhysicalCPUCoreCount   = ccci.PhysicalCPUCoreCount,
            LogicalCPUCount        = cci.NumberOfLogicalProcessors,
            TotalMachineMemoryMB   = oi.TotalVisibleMemorySize
     FROM   tempdb.dbo.tempGetMachineInfoOSInfo oi INNER JOIN tempdb.dbo.tempGetMachineInfoCPUCntInfo cci
               ON oi.PackageExecutionId = cci.PackageExecutionId
              AND oi.MachineName        = cci.MachineName
            INNER JOIN ( SELECT PackageExecutionId, 
                                MachineName,
                                MaxClockSpeed = MAX( MaxClockSpeed ),
                                PhysicalCPUCoreCount = SUM(NumberOfCores)
                         FROM   tempdb.dbo.tempGetMachineInfoCPUInfo
                         WHERE  PackageExecutionId = @PackageExecutionId
                         GROUP BY PackageExecutionId, MachineName ) ccci
               ON oi.PackageExecutionId = ccci.PackageExecutionId
              AND oi.MachineName        = ccci.MachineName
     WHERE  oi.PackageExecutionId    = @PackageExecutionId

     -- Get Cluster Name from Machine if it is already there
     UPDATE @MachineInfo
     SET    ClusterVirtualNameFlag = 1
     FROM   @MachineInfo mi INNER JOIN dbo.Machine m
               ON mi.MachineName = m.MachineName
     WHERE  m.ClusterVirtualNameFlag = 1

     -- Also Try the WMI Cluster Table
     UPDATE @MachineInfo
     SET    ClusterVirtualNameFlag = 1
     FROM   @MachineInfo mi INNER JOIN tempdb.dbo.tempGetMachineInfoCluster c
               ON mi.MachineName = c.ClusterName

     -- Walk Through the machines first, we'll do cluster stuff later.
     DECLARE Machine CURSOR FOR SELECT RecId
                                FROM   @MachineInfo
                                WHERE  ClusterVirtualNameFlag = 0

     OPEN Machine

     FETCH NEXT FROM Machine INTO @RecId

     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          SELECT @MachineName          = m.MachineName,
                 @PhysicalCPUCount     = m.PhysicalCPUCount,
                 @PhysicalCPUCoreCount = m.PhysicalCPUCoreCount,
                 @LogicalCPUCoreCount  = m.LogicalCPUCount,
                 @MaxCPUSpeedMHz       = m.MaxClockSpeed,
                 @OSVersion            = m.OSVersion,
                 @OSLevel              = m.OSLevel,
                 @OSArchitecture       = m.OSArchitecture,
                 @OSEdition            = m.OSEdition,
                 @TotalMachineMemoryMB = m.TotalMachineMemoryMB
          FROM   @MachineInfo m
          WHERE  RecId = @RecId

          EXEC dbo.SaveMachine
                    @PackageExecutionId          = @PackageExecutionId,
                    @ComputerNamePhysicalNetBIOS = @MachineName,
                    @MachineName                 = @MachineName,
                    @FQMachineName               = NULL,
                    @PhysicalCPUCount            = @PhysicalCPUCount,
                    @PhysicalCPUCoreCount        = @PhysicalCPUCoreCount,
                    @LogicalCPUCoreCount         = @LogicalCPUCoreCount,
                    @MaxCPUSpeedMHz              = @MaxCPUSpeedMHz,
                    @OSVersion                   = @OSVersion,
                    @OSLevel                     = @OSLevel,
                    @OSArchitecture              = @OSArchitecture,
                    @OSEdition                   = @OSEdition,
                    @TotalMachineMemoryMB        = @TotalMachineMemoryMB,
                    @SuppressResultSetFlag       = 1

          FETCH NEXT FROM Machine INTO @RecId
     END

     CLOSE Machine
     DEALLOCATE Machine

     -- Get Missing Cluster Nodes
     INSERT dbo.Machine
          ( PackageExecutionId,
            EnabledFlag,
            MachineName,
            FQMachineName,
            ClusterVirtualNameFlag,
            LastModDt )
     OUTPUT INSERTED.MachineId, INSERTED.MachineName INTO @MissingNodes
     SELECT DISTINCT 
            @PackageExecutionId,
            1, -- EnabledFlag
            c.NodeName,
            c.NodeName,
            0, --ClusterVirtualNameFlag
            CURRENT_TIMESTAMP
     FROM   tempdb.dbo.tempGetMachineInfoClusterToNode c
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.Machine m
                         WHERE  c.NodeName = m.MachineName
                         OR     c.NodeName = m.FQMachineName )
     AND    c.PackageExecutionId = @PackageExecutionId

     -- Get Missing Cluster Virtual Names
     INSERT dbo.Machine
          ( PackageExecutionId,
            EnabledFlag,
            MachineName,
            FQMachineName,
            ClusterVirtualNameFlag,
            LastModDt )
     OUTPUT INSERTED.MachineId, INSERTED.MachineName INTO @MissingClusters
     SELECT DISTINCT 
            @PackageExecutionId,
            1, -- EnabledFlag
            c.ClusterName,
            c.ClusterName,
            1, --ClusterVirtualNameFlag
            CURRENT_TIMESTAMP
     FROM   tempdb.dbo.tempGetMachineInfoCluster c
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.Machine m
                         WHERE  c.ClusterName = m.MachineName
                         OR     c.ClusterName = m.FQMachineName )
     AND    c.PackageExecutionId = @PackageExecutionId

     -- Assign Machines To Clusters
     INSERT dbo.MachineCluster
          ( ClusterMachineId,
            MemberMachineId,
            PackageExecutionId,
            LastModDt )
     SELECT wmc.ClusterMachineId,
            wmc.MemberMachineId,
            @PackageExecutionId,
            CURRENT_TIMESTAMP     
     FROM   ( SELECT DISTINCT 
                     ClusterMachineId = cm.MachineId,
                     MemberMachineId  = mm.MachineId
              FROM   dbo.Machine cm INNER JOIN tempdb.dbo.tempGetMachineInfoCluster tc
                        ON cm.MachineName = tc.ClusterName
                     INNER JOIN tempdb.dbo.tempGetMachineInfoClusterToNode tcn
                        ON tcn.ClusterName = tc.ClusterName
                     INNER JOIN dbo.Machine mm
                        ON mm.MachineName = tcn.NodeName
              WHERE  tc.PackageExecutionId  = @PackageExecutionId
              AND    tcn.PackageExecutionId = @PackageExecutionId ) wmc
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.MachineCluster mc
                         WHERE  mc.ClusterMachineId = wmc.ClusterMachineId
                         AND    mc.MemberMachineId  = wmc.MemberMachineId )

     -- Remove Machines Not in a cluster anymore
     DELETE dbo.MachineCluster
     FROM   dbo.MachineCluster mcd
     WHERE  NOT EXISTS ( SELECT 1
                         FROM   dbo.MachineCluster mc INNER JOIN dbo.Machine cm
                                   ON mc.ClusterMachineId = cm.MachineId
                                INNER JOIN dbo.Machine mm
                                   ON mc.MemberMachineId = mm.MachineId
                                INNER JOIN tempdb.dbo.tempGetMachineInfoClusterToNode tcn
                                   ON tcn.ClusterName = cm.MachineName
                                  AND tcn.NodeName    = mm.MachineName
                         WHERE  cm.MachineId           = mcd.ClusterMachineId
                         AND    mm.MachineId           = mcd.MemberMachineId
                         AND    tcn.PackageExecutionId = @PackageExecutionId )
     -- BUT don't touch clusters that are not in the data set
     AND    EXISTS ( SELECT 1
                     FROM   tempdb.dbo.tempGetMachineInfoClusterToNode tcn
                            INNER JOIN dbo.Machine cm
                              ON tcn.ClusterName = cm.MachineName
                     WHERE  cm.MachineId = mcd.ClusterMachineId )

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Volumes
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- Fill table variables
     INSERT @ClusterVolumeWithMountPoint
          ( MachineId,
            MachineName,
            ClusterVirtualNameFlag,
            PackageExecutionId,
            DiskId,
            ClusterDiskName,
            DiskPartitionPath,
            VolumeGUID,
            VolumeLabel,
            SerialNumber )
     SELECT DISTINCT 
            m.MachineId,
            m.MachineName,
            m.ClusterVirtualNameFlag,
            d.PackageExecutionId,
            DiskId          = d.Id,
            ClusterDiskName = d.NAME,
            dtdp.DiskPartitionPath,
            dp.VolumeGUID,
            dp.VolumeLabel,
            dp.SerialNumber
     FROM   dbo.Machine m INNER JOIN tempdb.dbo.tempGetMachineInfoClusterDisk d
               ON m.MachineName = d.MachineName
            INNER JOIN tempdb.dbo.tempGetMachineInfoClusterDiskToDiskPartition dtdp
               ON d.MachineName        = dtdp.MachineName 
              AND d.ID                 = dtdp.DiskID
              AND d.PackageExecutionId = dtdp.PackageExecutionID
            INNER JOIN tempdb.dbo.tempGetMachineInfoClusterDiskPartition dp
               ON dp.MachineName        = dtdp.MachineName
              AND dp.Path               = dtdp.DiskPartitionPath
              AND dp.PackageExecutionId = dp.PackageExecutionId
     WHERE  d.PackageExecutionId = @PackageExecutionId

     INSERT @VolumeWithMountPoint
          ( MachineId,
            MachineName,
            ClusterVirtualNameFlag,
            PackageExecutionId,
            DeviceID,
            Name,
            Label,
            BlockSize,
            Capacity,
            FreeSpace, 
            CompressedFlag,
            DriveTypeDesc,
            SerialNumber,
            FileSystem,
            MountPoint )
     SELECT DISTINCT 
            m.MachineId,
            m.MachineName,
            m.ClusterVirtualNameFlag,
            v.PackageExecutionId,
            v.DeviceID,
            v.Name,
            v.Label,
            v.BlockSize,
            v.Capacity,
            v.FreeSpace, 
            CompressedFlag = CASE v.Compressed WHEN 'FALSE' THEN 0 WHEN 'TRUE' THEN 1 ELSE NULL END,
            DriveTypeDesc = CASE v.DriveType WHEN 1 THEN 'No Root Directory'
                                             WHEN 2 THEN 'Removable Disk'
                                             WHEN 3 THEN 'Local Disk'
                                             WHEN 4 THEN 'Network Drive'
                                             WHEN 5 THEN 'Compact Disk'
                                             WHEN 6 THEN 'RAM Disk'
                                             ELSE 'Unknown'
                            END,
            v.SerialNumber,
            v.FileSystem,
            mp.MountPoint
     FROM   dbo.Machine m INNER JOIN tempdb.dbo.tempGetMachineInfoVolume v
               ON m.MachineName = v.MachineName
            LEFT OUTER JOIN tempdb.dbo.tempGetMachineInfoMountPoint mp
               ON v.DeviceID           = mp.DeviceID
              AND v.MachineName        = mp.MachineName
              AND v.PackageExecutionId = mp.PackageExecutionId
     WHERE  v.PackageExecutionId = @PackageExecutionId

     -- Do volumes for all machines, local and cluster
     DECLARE Volumes CURSOR FOR SELECT RecId
                                FROM   @VolumeWithMountPoint v
                                WHERE  NOT EXISTS ( SELECT 1
                                                    FROM   @ClusterVolumeWithMountPoint cv
                                                    WHERE  cv.SerialNumber  = v.SerialNumber
                                                    AND    cv.MachineId     = v.MachineId )
                                AND    v.ClusterVirtualNameFlag = 0
                                UNION ALL
                                SELECT v.RecId
                                FROM   @ClusterVolumeWithMountPoint cv
                                       INNER JOIN @VolumeWithMountPoint v
                                          ON cv.SerialNumber       = v.SerialNumber
                                         AND cv.MachineId          = v.MachineId
                                         AND cv.PackageExecutionId = v.PackageExecutionId
                                WHERE  cv.PackageExecutionId = @PackageExecutionId
                                AND    cv.ClusterVirtualNameFlag = 1

     OPEN Volumes
     
     FETCH NEXT FROM Volumes INTO @RecId
     
     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          SELECT @ClusterFlag             = v.ClusterVirtualNameFlag,
                 @MachineId               = v.MachineId,
                 @VolumeDeviceId          = v.DeviceId,
                 @VolumeMountPoint        = v.MountPoint,
                 @VolumeBlockSize         = v.BlockSize,
                 @VolumeCapacity          = v.Capacity,
                 @VolumeFreeSpace         = v.FreeSpace,
                 @VolumeCompressedFlag    = v.CompressedFlag,
                 @VolumeDriveTypeDesc     = v.DriveTypeDesc,
                 @VolumeFileSystemType    = v.FileSystem,
                 @VolumeLabel             = v.Label,
                 @VolumeName              = v.Name,
                 @VolumeSerialNumber      = v.SerialNumber
          FROM   @VolumeWithMountPoint v
          WHERE  v.RecId = @RecId

          EXEC dbo.SaveMachineDriveVolume
                    @MachineId               = @MachineId,
                    @PackageExecutionId      = @PackageExecutionId,
                    @VolumeDeviceId          = @VolumeDeviceId,
                    @VolumeMountPoint        = @VolumeMountPoint,
                    @VolumeBlockSize         = @VolumeBlockSize,
                    @VolumeCapacity          = @VolumeCapacity,
                    @VolumeCompressedFlag    = @VolumeCompressedFlag,
                    @VolumeDriveTypeDesc     = @VolumeDriveTypeDesc,
                    @VolumeFileSystemType    = @VolumeFileSystemType,
                    @VolumeLabel             = @VolumeLabel,
                    @VolumeName              = @VolumeName,
                    @VolumeSerialNumber      = @VolumeSerialNumber,
                    @ClusterSharedVolumeFlag = @ClusterFlag,
                    @VolumeDeletedFlag       = 0,
                    @MachineDriveVolumeId    = @MachineDriveVolumeId OUTPUT
     
          EXEC dbo.InsMachineDriveVolumeSpace
                    @MachineId            = @MachineId,
                    @PackageExecutionId   = @PackageExecutionId,
                    @MachineDriveVolumeId = @MachineDriveVolumeId,
                    @VolumeDeviceId       = @VolumeDeviceId,
                    @VolumeCapacity       = @VolumeCapacity,
                    @VolumeFreeSpace      = @VolumeFreeSpace
          
          FETCH NEXT FROM Volumes INTO @RecId
     END

     CLOSE Volumes
     DEALLOCATE Volumes

     -- Perform Volume "Deletions"
     DECLARE VolumeDeletes CURSOR FOR SELECT dv.MachineId, dv.VolumeDeviceId -- , dv.MachineDriveVolumeId
                                      FROM   dbo.MachineDriveVolume dv
                                      WHERE  NOT EXISTS ( SELECT 1
                                                          FROM   @VolumeWithMountPoint v
                                                          WHERE  v.MachineId = dv.MachineId
                                                          AND    v.DeviceId  = dv.VolumeDeviceId )
                                      -- But only for machines in the data set, don't delete others.
                                      AND    EXISTS ( SELECT 1
                                                      FROM   @VolumeWithMountPoint v
                                                      WHERE  v.MachineId = dv.MachineId )

     OPEN VolumeDeletes

     FETCH NEXT FROM VolumeDeletes INTO @MachineId, @VolumeDeviceId -- , @MachineDriveVolumeId

     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          EXEC dbo.SaveMachineDriveVolume
                    @MachineId               = @MachineId,
                    @PackageExecutionId      = @PackageExecutionId,
                    @VolumeDeviceId          = @VolumeDeviceId,
                    @VolumeMountPoint        = NULL,
                    @VolumeBlockSize         = NULL,
                    @VolumeCapacity          = NULL,
                    @VolumeCompressedFlag    = NULL,
                    @VolumeDriveTypeDesc     = NULL,
                    @VolumeFileSystemType    = NULL,
                    @VolumeLabel             = NULL,
                    @VolumeName              = NULL,
                    @VolumeSerialNumber      = NULL,
                    @ClusterSharedVolumeFlag = NULL,
                    @VolumeDeletedFlag      = 1

          FETCH NEXT FROM VolumeDeletes INTO @MachineId, @VolumeDeviceId -- , @MachineDriveVolumeId
     END

     CLOSE VolumeDeletes
     DEALLOCATE VolumeDeletes

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- Environment Variables
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- Fill Table Variables
     INSERT @EnvVar
          ( MachineId,
            MachineName,
            ClusterVirtualNameFlag,
            PackageExecutionId,
            VarName,
            VarUser,
            VarValue )
     SELECT DISTINCT
            m.MachineId,
            m.MachineName,
            m.ClusterVirtualNameFlag,
            e.PackageExecutionId,
            e.VarName,
            e.VarUser,
            e.VarValue
     FROM   dbo.Machine m INNER JOIN tempdb.dbo.tempGetMachineInfoEnvVar e
               ON m.MachineName = e.MachineName
     WHERE  e.PackageExecutionId = @PackageExecutionId

     DECLARE EnvVars CURSOR FOR SELECT RecId
                                FROM   @EnvVar
                                WHERE  ClusterVirtualNameFlag = 0 -- No cluster vnames

     OPEN EnvVars
     
     FETCH NEXT FROM EnvVars INTO @RecId
     
     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          SELECT @ClusterFlag = e.ClusterVirtualNameFlag,
                 @MachineId   = e.MachineId,
                 @VarName     = e.VarName,
                 @VarUser     = e.VarUser,
                 @VarValue    = e.VarValue
          FROM   @EnvVar e
          WHERE  e.RecId = @RecId

          EXEC dbo.SaveMachineEnvVar
                    @MachineId          = @MachineId,
                    @PackageExecutionId = @PackageExecutionId,
                    @VarName            = @VarName,
                    @VarUser            = @VarUser,
                    @VarVal             = @VarValue,
                    @VarDeletedFlag     = 0
          FETCH NEXT FROM EnvVars INTO @RecId
     END

     CLOSE EnvVars
     DEALLOCATE EnvVars

     -- Perform cluster "deletes", any machine that is a cluster vname will have
     -- any defined environment variables removed.  This process will not insert
     -- then anyway, however, in the odd case that a stand alone machine existed
     -- and then that name was used for a cluster vname this handles it.  We also
     -- handle regular deletes here since the logic is effectively the same.
     DECLARE EnvVarsDelete CURSOR FOR SELECT mev.MachineId, mev.VarName, mev.VarUser
                                      FROM   dbo.Machine m INNER JOIN dbo.MachineEnvVar mev
                                                ON m.MachineId = mev.MachineId
                                      WHERE  m.ClusterVirtualNameFlag = 1
                                      UNION ALL
                                      -- Handle Regular deletes too..
                                      SELECT mev.MachineId, mev.VarName, mev.VarUser
                                      FROM   dbo.MachineEnvVar mev
                                      WHERE  NOT EXISTS ( SELECT 1
                                                          FROM   @EnvVar e
                                                          WHERE  mev.MachineId = e.MachineId
                                                          AND    mev.VarName   = e.VarName
                                                          AND    mev.VarUser   = e.VarUser ) 
                                      -- Don't touch machines not in the data
                                      AND    EXISTS ( SELECT 1
                                                      FROM   @EnvVar e
                                                      WHERE  e.MachineId = mev.MachineId )

     OPEN EnvVarsDelete
     
     FETCH NEXT FROM EnvVarsDelete INTO @MachineId, @VarName, @VarUser

     WHILE ( @@FETCH_STATUS = 0 )
     BEGIN
          EXEC dbo.SaveMachineEnvVar
                    @MachineId          = @MachineId,
                    @PackageExecutionId = @PackageExecutionId,
                    @VarName            = @VarName,
                    @VarUser            = @VarUser,
                    @VarVal             = NULL,
                    @VarDeletedFlag     = 1

          FETCH NEXT FROM EnvVarsDelete INTO @MachineId, @VarName, @VarUser
     END

     CLOSE EnvVarsDelete
     DEALLOCATE EnvVarsDelete

     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- 
     -- End
     -- 
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------
     -- ------------------------------------------------------------------------

     -- Consolidate Records
     INSERT @MissingNodes
          ( MachineId,
            MachineName )
     SELECT MachineId,
            MachineName
     FROM   @MissingClusters
     ORDER BY MachineId

     -- Give result set of missing nodes for next pass.
     SELECT @RV = COUNT(*) FROM @MissingNodes

     SELECT MachineId, MachineName FROM @MissingNodes

     RETURN @RV
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Due to the complexity of determinations about clusters, cluster nodes, cluster drive volumes, and such, this sproc handles the logic needed to add any extra machines.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveMachineInfoFromWMI;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMachineSrvrInstncMachine' AND type = 'P')
     DROP PROCEDURE dbo.SaveMachineSrvrInstncMachine
GO

CREATE PROCEDURE dbo.SaveMachineSrvrInstncMachine
     @SrvrInstncId                int,
     @PackageExecutionId          bigint,
     @ComputerNamePhysicalNetBIOS varchar(128) = NULL,
     @MachineName                 varchar(128) = NULL,
     @FQMachineName               varchar(255) = NULL,
     @PhysicalCPUCount            int          = NULL,
     @PhysicalCPUCoreCount        int          = NULL,
     @LogicalCPUCoreCount         int          = NULL,
     @MaxCPUSpeedMHz              INT          = NULL,
     @OSVersion                   VARCHAR(30)  = NULL,
     @OSLevel                     varchar(30)  = NULL,
     @OSArchitecture              varchar(10)  = NULL,
     @OSEdition                   varchar(128) = NULL,
     @TotalMachineMemoryMB        int          = NULL
AS
/*
 *
 * SaveMachineSrvrInstncMachine
 *
 * Purpose:      To provide a single interface to both the
 *               dbo.SaveMachine and dbo.SaveSrvrInstncMachine
 *               sprocs in the same call, this is useful for the SSIS data flow
 *               where it would be tricky to get the server machine id and pass
 *               it on to a later call.
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @MachineId int
     
     -- Handle the SrvrMachine First
     EXEC dbo.SaveMachine
               @PackageExecutionId          = @PackageExecutionId,
               @ComputerNamePhysicalNetBIOS = @ComputerNamePhysicalNetBIOS,
               @MachineName                 = @MachineName,
               @FQMachineName               = @FQMachineName,
               @PhysicalCPUCount            = @PhysicalCPUCount,
               @PhysicalCPUCoreCount        = @PhysicalCPUCoreCount,
               @LogicalCPUCoreCount         = @LogicalCPUCoreCount,
               @MaxCPUSpeedMHz              = @MaxCPUSpeedMHz,
               @OSVersion                   = @OSVersion,
               @OSLevel                     = @OSLevel,
               @OSArchitecture              = @OSArchitecture,
               @OSEdition                   = @OSEdition,
               @TotalMachineMemoryMB        = @TotalMachineMemoryMB,
               @MachineId                   = @MachineId OUTPUT

     IF ( @MachineId IS NOT NULL )
     BEGIN
          EXEC dbo.SaveSrvrInstncMachine
               @SrvrInstncId       = @SrvrInstncId,
               @MachineId          = @MachineId,
               @PackageExecutionId = @PackageExecutionId 
     END
     ELSE
     BEGIN
          PRINT 'Machine Id not available.'
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'This stored procedure does no real work itself, it provides a method to write server machine and server instance machine record, it calls the underlying sprocs SaveSrvrMachine and SaveSrvrInstncMachine in that order.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveMachineSrvrInstncMachine;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMaxEventLogId' AND type = 'P')
     DROP PROCEDURE dbo.SaveMaxEventLogId
GO

CREATE PROCEDURE dbo.SaveMaxEventLogId
     @SrvrInstncDatabaseId  int,
     @MaxEventLogId         varchar(20) = NULL OUTPUT, -- Optional Parameter
     @SuppressResultsetFlag tinyint     = 0 -- Optional Parameter
AS
/*
 *
 * SaveMaxEventLogId
 *
 * Purpose:      To Calculate and save the MaxEventLogId
 *               for the specified server.
 *
 * Inputs:       @SrvrInstncDatabaseId
 *
 * Assumes:      
 *
 * Effects:      Database is updated, or record is added
 *
 * Returns:      Nothing
 *
 * Note(s):      As a paranoia step if you force @SrvrInstncDatabaseId to NULL, 
 *               it will update ALL Max EventLog Ids for any server instance
 *               that has history.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/04/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @ParameterId  INT

     -- We need this everywhere so we set it early.
     SELECT @ParameterId  = dbo.GetParameterIdByParameterCd( 'MaxEventLogId' )
     
     -- We want to make sure we start at NULL
     SELECT @MaxEventLogId = NULL
     
     -- Determine if we are doing one or all.
     IF ( @SrvrInstncDatabaseId IS NOT NULL )
     BEGIN -- Doing one.
          DECLARE @SrvrInstncId     int,
                  --@MaxEventLogId    bigint, -- declared above.
                  --@ParameterMultiId int,
                  @msg              varchar(80)

          -- Determine max id.
          SELECT @MaxEventLogId = MAX(EventLogId)
          FROM   dbo.MasterEventLog 
          WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId 

          -- Get the Server Instance Id
          SELECT @SrvrInstncId = SrvrInstncId
          FROM   dbo.SrvrInstncDatabase
          WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId

          -- Determine if record exists
          IF ( dbo.GetParameterCdExistsBySrvrInstncIdMultiId( @SrvrInstncId, 
                                                              @SrvrInstncDatabaseId,
                                                              'MaxEventLogId' ) = 1 )
          BEGIN -- Record already exists so we do update
               UPDATE dbo.SrvrInstncEAV
               SET    ParameterValue = @MaxEventLogId,
                      LastModDt      = CURRENT_TIMESTAMP 
               WHERE  SrvrInstncId     = @SrvrInstncId 
               AND    ParameterId      = @ParameterId
               AND    ParameterMultiId = @SrvrInstncDatabaseId -- @ParameterMultiId 

               IF ( @@ROWCOUNT != 1 )
               BEGIN
                    SELECT @msg = 'The update of the MaxEventLogId for SrvrInstncDatabaseId: '
                                + CONVERT( varchar(11), @SrvrInstncDatabaseId )
                                + ' Failed'

                    RAISERROR( @msg, 16, 1 )
               END
               ELSE
               BEGIN
                    -- Return resultset if allowed
                    IF ( @SuppressResultsetFlag != 1 )
                    BEGIN
                         SELECT SrvrInstncId,
                                ParameterId,
                                ParameterMultiId,
                                ParameterValue
                         FROM   dbo.SrvrInstncEAV
                         WHERE  SrvrInstncId      = @SrvrInstncId
                         AND    ParameterId       = @ParameterId
                         AND    ParameterMultiId  = @SrvrInstncDatabaseId
                    END
               END
          END
          ELSE
          BEGIN
               INSERT dbo.SrvrInstncEAV
                    ( SrvrInstncId,
                      ParameterId,
                      ParameterMultiId,
                      ParameterValue )
               SELECT @SrvrInstncId,
                      @ParameterId,
                      @SrvrInstncDatabaseId,
                      @MaxEventLogId 

               IF ( @@ROWCOUNT != 1 )
               BEGIN
                    SELECT @msg = 'The insert of the MaxEventLogId for SrvrInstncDatabaseId: '
                                + CONVERT( varchar(11), @SrvrInstncDatabaseId )
                                + ' Failed'

                    RAISERROR( @msg, 16, 1 )
               END
               ELSE
               BEGIN
                    -- Return resultset if allowed
                    IF ( @SuppressResultsetFlag != 1 )
                    BEGIN
                         SELECT SrvrInstncId,
                                ParameterId,
                                ParameterMultiId,
                                ParameterValue
                         FROM   dbo.SrvrInstncEAV
                         WHERE  SrvrInstncId      = @SrvrInstncId
                         AND    ParameterId       = @ParameterId
                         AND    ParameterMultiId  = @SrvrInstncDatabaseId
                    END
               END
          END
     END
     ELSE 
     BEGIN -- @ServerInstanceId is NULL, do all of them.
          DECLARE @Server TABLE ( SrvrInstncId         int           NOT NULL,
                                  SrvrInstncDatabaseId int           NOT NULL PRIMARY KEY,
                                  MaxEventLogId        varchar(8000) NOT NULL )

          -- Get all server ids and maximums
          INSERT @Server 
               ( SrvrInstncId,
                 SrvrInstncDatabaseId,
                 MaxEventLogId )
          SELECT sid.SrvrInstncId,
                 mel.SrvrInstncDatabaseId,
                 MAX(mel.EventLogId)
          FROM   dbo.MasterEventLog mel INNER JOIN dbo.SrvrInstncDatabase sid
                    ON mel.SrvrInstncDatabaseId = sid.SrvrInstncDatabaseId
          GROUP BY sid.SrvrInstncId, mel.SrvrInstncDatabaseId 

          -- Update any that already exist, we do this first on purpose.
          UPDATE dbo.SrvrInstncEAV
          SET    ParameterValue = s.MaxEventLogId,
                 LastModDt      = CURRENT_TIMESTAMP 
          FROM   dbo.SrvrInstncEAV sie INNER JOIN @Server s
                    ON sie.SrvrInstncId     = s.SrvrInstncId
                   AND sie.ParameterMultiId = s.SrvrInstncDatabaseId
                   AND sie.ParameterId      = @ParameterId
          WHERE  sie.ParameterValue != s.MaxEventLogId 
          OR     sie.ParameterValue IS NULL

          -- Insert the new ones, making extra sure that we don't add a dupe
          INSERT dbo.SrvrInstncEAV
               ( SrvrInstncId,
                 ParameterId,
                 ParameterMultiId,
                 ParameterValue )
          SELECT s.SrvrInstncId,
                 @ParameterId,
                 s.SrvrInstncDatabaseId,
                 s.MaxEventLogId 
          FROM   @Server s
          WHERE  NOT EXISTS ( SELECT 'X' 
                              FROM   dbo.SrvrInstncEAV siem
                              WHERE  siem.SrvrInstncId     = s.SrvrInstncId
                              AND    siem.ParameterId      = @ParameterId
                              AND    siem.ParameterMultiId = s.SrvrInstncDatabaseId  )

          -- Return resultset if allowed
          IF ( @SuppressResultsetFlag != 1 )
          BEGIN
               SELECT siem.SrvrInstncId,
                      siem.ParameterId,
                      siem.ParameterMultiId,
                      siem.ParameterValue
               FROM   dbo.SrvrInstncEAV siem INNER JOIN @Server s
                         ON siem.SrvrInstncId     = s.SrvrInstncId
                        AND siem.ParameterMultiId = s.SrvrInstncDatabaseId
                        AND siem.ParameterId      = @ParameterId
          END

     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Calculate and save the maximum EventLogId in MasterEventLog for a specified server instance and database on that server instance.  This is used to determine what records are retrieved during the next collection run so that the whole table is not collected and only the new records (as far as the MasterEventLog is concerned) are retrieved.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveMaxEventLogId;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveMaxMSSQLSchedJobHistoryId' AND type = 'P')
     DROP PROCEDURE dbo.SaveMaxMSSQLSchedJobHistoryId
GO

CREATE PROCEDURE dbo.SaveMaxMSSQLSchedJobHistoryId
     @SrvrInstncId int = NULL -- Optional Parameter, leave NULL for an update to ALL.
AS
/*
 *
 * SaveMaxMSSQLSchedJobHistoryId
 *
 * Purpose:      To Calculate and save the MaxSchedJobHistoryId
 *               for the specified server.
 *
 * Inputs:       @SrvrInstncId
 *
 * Assumes:      
 *
 * Effects:      Database is updated, or record is added
 *
 * Returns:      Nothing
 *
 * Note(s):      As a paranoia step if you force @SrvrInstncId to NULL, 
 *               it will update ALL Max Job History Ids for any server instance
 *               that has history.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/31/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @ParameterId int

     -- We need this everywhere so we set it early.
     SELECT @ParameterId  = dbo.GetParameterIdByParameterCd( 'MaxJobHistoryId' )
     
     -- Determine if we are doing one or all.
     IF ( @SrvrInstncId IS NOT NULL )
     BEGIN
          DECLARE @MaxJobHistoryId  bigint,
                  @msg              varchar(80)

          -- Determine max id.
          SELECT @MaxJobHistoryId = ISNULL(MAX(JobHistoryId),0)
          FROM   dbo.SrvrInstncSchedJobHistoryMSSQL
          WHERE  SrvrInstncId = @SrvrInstncId

          -- Determine if record exists
          IF ( dbo.GetParameterCdExistsBySrvrInstncId( @SrvrInstncId, 
                                                       'MaxJobHistoryId' ) = 1 )
          BEGIN -- Record already exists so we do update
               UPDATE dbo.SrvrInstncEAV
               SET    ParameterValue = @MaxJobHistoryId,
                      LastModDt      = CURRENT_TIMESTAMP 
               WHERE  SrvrInstncId     = @SrvrInstncId 
               AND    ParameterId      = @ParameterId

               IF ( @@ROWCOUNT != 1 )
               BEGIN
                    SELECT @msg = 'The update of the MaxJobHistoryId for ServerInstanceId: '
                                + CONVERT( varchar(11), @SrvrInstncId )
                                + ' Failed'

                    RAISERROR( @msg, 16, 1 )
               END
          END
          ELSE
          BEGIN
               INSERT dbo.SrvrInstncEAV
                    ( SrvrInstncId,
                      ParameterId,
                      ParameterValue )
               SELECT @SrvrInstncId,
                      @ParameterId,
                      @MaxJobHistoryId 

               IF ( @@ROWCOUNT != 1 )
               BEGIN
                    SELECT @msg = 'The insert of the MaxJobHistoryId for ServerInstanceId: '
                                + CONVERT( varchar(11), @SrvrInstncId )
                                + ' Failed'

                    RAISERROR( @msg, 16, 1 )
               END
          END
          
          SELECT SrvrInstncId    = @SrvrInstncId, 
                 MaxJobHistoryId = @MaxJobHistoryId
     END
     ELSE 
     BEGIN -- @ServerInstanceId is NULL, do all of them.
          DECLARE @Server TABLE ( SrvrInstncId    int           NOT NULL,
                                  MaxJobHistoryId varchar(8000) NOT NULL )

          -- Get all server ids and maximums
          INSERT @Server 
               ( SrvrInstncId,
                 MaxJobHistoryId )
          SELECT SrvrInstncId,
                 ISNULL(MAX(JobHistoryId),0)
          FROM   dbo.SrvrInstncSchedJobHistoryMSSQL
          GROUP BY SrvrInstncId

          -- Update any that already exist, we do this first on purpose.
          UPDATE dbo.SrvrInstncEAV
          SET    ParameterValue = s.MaxJobHistoryId,
                 LastModDt      = CURRENT_TIMESTAMP 
          FROM   dbo.SrvrInstncEAV sie INNER JOIN @Server s
                    ON sie.SrvrInstncId = s.SrvrInstncId
                   AND sie.ParameterId  = @ParameterId
          WHERE  sie.ParameterValue != s.MaxJobHistoryId 
          OR     sie.ParameterValue IS NULL

          -- Insert the new ones, making extra sure that we don't add a dupe
          INSERT dbo.SrvrInstncEAV
               ( SrvrInstncId,
                 ParameterId,
                 ParameterValue )
          SELECT s.SrvrInstncId,
                 @ParameterId,
                 s.MaxJobHistoryId 
          FROM   @Server s
          WHERE  NOT EXISTS ( SELECT 'X' 
                              FROM   dbo.SrvrInstncEAV sie
                              WHERE  sie.SrvrInstncId = s.SrvrInstncId
                              AND    sie.ParameterId  = @ParameterId )

          SELECT SrvrInstncId, 
                 MaxJobHistoryId = CONVERT( bigint, MaxJobHistoryId )
          FROM   @Server 
     END

END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Calculate and save the maximum JobHistoryId in SrvrInstncSchedJobHistoryMSSQL for a specified server instance.  This is used to determine what records are retrieved during the next collection run so that the whole table is not collected and only the new records (as far as the SrvrInstncMSSQLSchedJobHistory is concerned) are retrieved.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveMaxMSSQLSchedJobHistoryId;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncCfg1MSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncCfg1MSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncCfg1MSSQL
     @SrvrInstncId               int,
     @PackageExecutionId         bigint,
     @ClusteredFlag              tinyint,
     @FullTextInstalledFlag      tinyint,
     @IntegratedSecurityOnlyFlag tinyint,
     @ProductVersion             varchar(30),
     @ProductLevel               varchar(30),
     @ServerEdition              varchar(128),
     @LicenseType                varchar(30),
     @NumberOfLicenses           int,
     @SrvrCollation              varchar(128),
     @SrvrMinMemoryMB            int,
     @SrvrMaxMemoryMB            int
AS
/*
 *
 * SaveSrvrInstncCfg1MSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 06/06/2009, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @NOW     datetime,
             @StartDt datetime

     -- Get current date/time 
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Generate place to hold current record
     DECLARE @CurrRec TABLE ( SrvrInstncId               int          NOT NULL,
                              PackageExecutionId         bigint       NOT NULL,
                              ClusteredFlag              tinyint          NULL,
                              FullTextInstalledFlag      tinyint          NULL,
                              IntegratedSecurityOnlyFlag tinyint          NULL,
                              ProductVersion             varchar(30)      NULL,
                              ProductLevel               varchar(30)      NULL,
                              ServerEdition              varchar(128)     NULL,
                              LicenseType                varchar(30)      NULL,
                              NumberOfLicenses           int              NULL,
                              SrvrCollation              varchar(128)     NULL,
                              SrvrMinMemoryMB            int              NULL,
                              SrvrMaxMemoryMB            int              NULL )

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncCfg1MSSQL
                     WHERE  SrvrInstncId = @SrvrInstncId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncCfg1MSSQL
               ( SrvrInstncId,
                 PackageExecutionId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 ClusteredFlag,
                 FullTextInstalledFlag,
                 IntegratedSecurityOnlyFlag,
                 ProductVersion,
                 ProductLevel,
                 ServerEdition,
                 LicenseType,
                 NumberOfLicenses,
                 SrvrCollation,
                 SrvrMinMemoryMB,
                 SrvrMaxMemoryMB )
          SELECT @SrvrInstncId,
                 @PackageExecutionId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @ClusteredFlag,
                 @FullTextInstalledFlag,
                 @IntegratedSecurityOnlyFlag,
                 @ProductVersion,
                 @ProductLevel,
                 @ServerEdition,
                 @LicenseType,
                 @NumberOfLicenses,
                 @SrvrCollation,
                 @SrvrMinMemoryMB,
                 @SrvrMaxMemoryMB
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncCfg1MSSQL
          WHERE  SrvrInstncId          = @SrvrInstncId
          AND    CurrentRecordFlag     = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncCfg1MSSQL
          SET    EndDt             = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag = 0
          WHERE  SrvrInstncId      = @SrvrInstncId
          AND    CurrentRecordFlag = 1

          -- We do the insert and use the last current record to fill in any NULLs
          -- that we might have gotten in this run, we don't want to lose anything
          -- that we already have.  We use COALESCE for this.
          INSERT dbo.SrvrInstncCfg1MSSQL
               ( SrvrInstncId,
                 PackageExecutionId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 ClusteredFlag,
                 FullTextInstalledFlag,
                 IntegratedSecurityOnlyFlag,
                 ProductVersion,
                 ProductLevel,
                 ServerEdition,
                 LicenseType,
                 NumberOfLicenses,
                 SrvrCollation,
                 SrvrMinMemoryMB,
                 SrvrMaxMemoryMB )
          SELECT @SrvrInstncId,
                 @PackageExecutionId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 COALESCE( @ClusteredFlag,              ClusteredFlag ),
                 COALESCE( @FullTextInstalledFlag,      FullTextInstalledFlag ),
                 COALESCE( @IntegratedSecurityOnlyFlag, IntegratedSecurityOnlyFlag ),
                 COALESCE( @ProductVersion,             ProductVersion ),
                 COALESCE( @ProductLevel,               ProductLevel ),
                 COALESCE( @ServerEdition,              ServerEdition ),
                 COALESCE( @LicenseType,                LicenseType ),
                 COALESCE( @NumberOfLicenses,           NumberOfLicenses ),
                 COALESCE( @SrvrCollation,              SrvrCollation ),
                 COALESCE( @SrvrMinMemoryMB,            SrvrMinMemoryMB ),
                 COALESCE( @SrvrMaxMemoryMB,            SrvrMaxMemoryMB )
          FROM   dbo.SrvrInstncCfg1MSSQL
          -- This is all kind of long, we don't want to write a record that has no 
          -- changes, but due to the NULLs possibilities we have to do a couple of
          -- comparisons, the first is that they don't equal, this is a simple check
          -- that assumes that neither the current record has a NULL or the COALESCE
          -- statement generates a NULL, in the cases that this happens the case will
          -- test as neither true OR false and will effectively be ignored, this is 
          -- ok for our purposes.  So in the second case we look to see if the current
          -- record is NULL for the field and if so whether the COALESCE'd fields are 
          -- NOT NULL, if they are we want to write a new record, this is the equivalent
          -- of getting update information where we didn't have it before.
          WHERE  SrvrInstncId = @SrvrInstncId
          AND    StartDt      = @StartDt
          AND  ( ( ClusteredFlag              != COALESCE( @ClusteredFlag,              ClusteredFlag )
                OR FullTextInstalledFlag      != COALESCE( @FullTextInstalledFlag,      FullTextInstalledFlag )
                OR IntegratedSecurityOnlyFlag != COALESCE( @IntegratedSecurityOnlyFlag, IntegratedSecurityOnlyFlag )
                OR ProductVersion             != COALESCE( @ProductVersion,             ProductVersion )
                OR ProductLevel               != COALESCE( @ProductLevel,               ProductLevel )
                OR ServerEdition              != COALESCE( @ServerEdition,              ServerEdition )
                OR LicenseType                != COALESCE( @LicenseType,                LicenseType )
                OR NumberOfLicenses           != COALESCE( @NumberOfLicenses,           NumberOfLicenses )
                OR SrvrCollation              != COALESCE( @SrvrCollation,              SrvrCollation )
                OR SrvrMinMemoryMB            != COALESCE( @SrvrMinMemoryMB,            SrvrMinMemoryMB )
                OR SrvrMaxMemoryMB            != COALESCE( @SrvrMaxMemoryMB,            SrvrMaxMemoryMB )
                 ) 
              OR ( ( ClusteredFlag              IS NULL 
                 AND COALESCE( @ClusteredFlag,              ClusteredFlag )              IS NOT NULL )
                OR ( FullTextInstalledFlag      IS NULL 
                 AND COALESCE( @FullTextInstalledFlag,      FullTextInstalledFlag )      IS NOT NULL )
                OR ( IntegratedSecurityOnlyFlag IS NULL 
                 AND COALESCE( @IntegratedSecurityOnlyFlag, IntegratedSecurityOnlyFlag ) IS NOT NULL )
                OR ( ProductVersion             IS NULL 
                 AND COALESCE( @ProductVersion,             ProductVersion )             IS NOT NULL )
                OR ( ProductLevel               IS NULL 
                 AND COALESCE( @ProductLevel,               ProductLevel )               IS NOT NULL )
                OR ( ServerEdition              IS NULL 
                 AND COALESCE( @ServerEdition,              ServerEdition )              IS NOT NULL )
                OR ( LicenseType                IS NULL 
                 AND COALESCE( @LicenseType,                LicenseType )                IS NOT NULL )
                OR ( NumberOfLicenses           IS NULL 
                 AND COALESCE( @NumberOfLicenses,           NumberOfLicenses )           IS NOT NULL )
                OR ( SrvrCollation              IS NULL 
                 AND COALESCE( @SrvrCollation,              SrvrCollation )              IS NOT NULL )
                OR ( SrvrMinMemoryMB            IS NULL 
                 AND COALESCE( @SrvrMinMemoryMB,            SrvrMinMemoryMB )            IS NOT NULL )
                OR ( SrvrMaxMemoryMB            IS NULL 
                 AND COALESCE( @SrvrMaxMemoryMB,            SrvrMaxMemoryMB )            IS NOT NULL )
                 )
               ) 

          -- Determine outcome.
          IF ( @@ROWCOUNT = 1 )
          BEGIN -- Record inserted, COMMIT it..
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- Record not inserted, do rollback, this isn't an error..
                -- If nothing is different we don't add the record but we also don't 
                -- want to have the current record updates kept either.
               ROLLBACK TRANSACTION
          END
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance config MS SQL specific record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncCfg1MSSQL;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncCfg2MSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncCfg2MSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncCfg2MSSQL
     @SrvrInstncId             int,
     @PackageExecutionId       bigint,
     @SysConfigurationId       int,
     @SysConfigurationName     varchar(255),
     @ConfigValue              bigint,
     @RunValue                 bigint
AS
/*
 *
 * SaveSrvrInstncCfg2MSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      Config deletes are not taken into account
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 12/05/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @IdForSrv    int,
             @StartDt     datetime,
             @RC          int,
             @NOW         datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncCfg2MSSQL
                     WHERE  SrvrInstncId        = @SrvrInstncId
                     AND    SysConfigurationId  = @SysConfigurationId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncCfg2MSSQL
               ( SrvrInstncId,
                 PackageExecutionId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 SysConfigurationId,
                 SysConfigurationName,
                 ConfigValue,
                 RunValue )
          SELECT @SrvrInstncId,
                 @PackageExecutionId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @SysConfigurationId,
                 @SysConfigurationName,
                 @ConfigValue,
                 @RunValue
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncCfg2MSSQL
          WHERE  SrvrInstncId       = @SrvrInstncId
          AND    SysConfigurationId = @SysConfigurationId
          AND    CurrentRecordFlag  = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncCfg2MSSQL
          SET    EndDt              = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag  = 0
          WHERE  SrvrInstncId       = @SrvrInstncId
          AND    SysConfigurationId = @SysConfigurationId
          AND    CurrentRecordFlag = 1

          -- Do regular insert
          INSERT dbo.SrvrInstncCfg2MSSQL
               ( SrvrInstncId,
                 PackageExecutionId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 SysConfigurationId,
                 SysConfigurationName,
                 ConfigValue,
                 RunValue )
          SELECT @SrvrInstncId,
                 @PackageExecutionId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @SysConfigurationId,
                 @SysConfigurationName,
                 @ConfigValue,
                 @RunValue
          FROM   dbo.SrvrInstncCfg2MSSQL
          WHERE  SrvrInstncId       = @SrvrInstncId
          AND    SysConfigurationId = @SysConfigurationId
          AND    StartDt            = @StartDt
          -- Decide if there will be an insert
          AND  ( @SysConfigurationName != SysConfigurationName
              OR @ConfigValue          != ConfigValue
              OR @RunValue             != RunValue
               ) -- End of And-Or section

          SELECT @RC = @@ROWCOUNT 

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncDatabase' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncDatabase
GO

CREATE PROCEDURE dbo.SaveSrvrInstncDatabase
     @SrvrInstncId             int,
     @PackageExecutionId       bigint,
     @DatabaseName             varchar(128),
     @DatabaseId               int           = NULL,
     @DatabaseOwnerName        varchar(128)  = NULL,
     @DateCreated              datetime      = NULL,
     @DatabaseReadOnlyFlag     tinyint       = NULL,
     @CompatibilityLevel       varchar(10)   = NULL,
     @Collation                varchar(128)  = NULL,
     @DBStatus                 varchar(30)   = NULL,
     @RecoveryModel            varchar(15)   = NULL,
     @AccessLevel              varchar(30)   = NULL,
     @AutoCloseFlag            tinyint       = NULL,
     @AutoCreateStatsFlag      tinyint       = NULL,
     @AutoShrinkFlag           tinyint       = NULL,
     @AutoUpdateStatsFlag      tinyint       = NULL,
     @AutoUpdateStatsAsyncFlag tinyint       = NULL,
     @RecursiveTriggersFlag    tinyint       = NULL,
     @TrustworthyFlag          tinyint       = NULL,
     @BrokerEnabledFlag        tinyint       = NULL,
     @EncryptionFlag           tinyint       = NULL,
     @DatabaseDeletedFlag      tinyint       = 0
AS
/*
 *
 * SaveSrvrInstncDatabase
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/20/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @DBIdForSrv       int,
             @StartDt          datetime,
             @SrvrInstncTypeId int,
             @MaxPEI           bigint,
             @RC               int,
             @NOW              datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Get The server Type
     SELECT @SrvrInstncTypeId = SrvrInstncTypeId
     FROM   dbo.SrvrInstnc 
     WHERE  SrvrInstncId = @SrvrInstncId

     -- Handle special case that the server is local, we can correct any values
     -- that are NULL
     IF EXISTS ( SELECT 'X' 
                 FROM   dbo.SrvrInstnc 
                 WHERE  SrvrInstncId       = @SrvrInstncId 
                 AND    SrvrInstncFullName = @@SERVERNAME )
     BEGIN
          SELECT @DatabaseId               = COALESCE( @DatabaseId, CONVERT( int, d.dbid ) ), 
                 @DatabaseOwnerName        = COALESCE( @DatabaseOwnerName, CONVERT( varchar(128), l.name ) ),
                 @DateCreated              = COALESCE( @DateCreated, CONVERT( datetime, d.crdate ) ), 
                 @DatabaseReadOnlyFlag     = COALESCE( @DatabaseReadOnlyFlag, CONVERT( tinyint, CASE DATABASEPROPERTYEX(d.name,'Updateability') WHEN N'READ_ONLY' THEN 1 ELSE 0 END ) ), 
                 @CompatibilityLevel       = COALESCE( @CompatibilityLevel, CONVERT( varchar(10), d.cmptlevel ) ), 
                 @Collation                = COALESCE( @Collation, CONVERT( varchar(128), DATABASEPROPERTYEX(d.name,'Collation') ) ), 
                 @DBStatus                 = COALESCE( @DBStatus, CONVERT( varchar(30), DATABASEPROPERTYEX(d.name,'Status') ) ), 
                 @RecoveryModel            = COALESCE( @RecoveryModel, CONVERT( varchar(15), DATABASEPROPERTYEX(d.name,'Recovery') ) ), 
                 @AccessLevel              = COALESCE( @AccessLevel, CONVERT( varchar(30), DATABASEPROPERTYEX(d.name,'UserAccess') ) ), 
                 @AutoCloseFlag            = COALESCE( @AutoCloseFlag, CONVERT( tinyint, DATABASEPROPERTYEX(d.name,'IsAutoClose') ) ), 
                 @AutoCreateStatsFlag      = COALESCE( @AutoCreateStatsFlag, CONVERT( tinyint, DATABASEPROPERTYEX(d.name,'IsAutoCreateStatistics') ) ), 
                 @AutoShrinkFlag           = COALESCE( @AutoShrinkFlag, CONVERT( tinyint, DATABASEPROPERTYEX(d.name,'IsAutoShrink ') ) ), 
                 @AutoUpdateStatsFlag      = COALESCE( @AutoUpdateStatsFlag, CONVERT( tinyint, DATABASEPROPERTYEX(d.name,'IsAutoUpdateStatistics') ) ), 
                 @AutoUpdateStatsAsyncFlag = COALESCE( @AutoUpdateStatsAsyncFlag, CONVERT( tinyint, NULL ) ), 
                 @RecursiveTriggersFlag    = COALESCE( @RecursiveTriggersFlag, CONVERT( tinyint, NULL ) ), 
                 @TrustworthyFlag          = COALESCE( @TrustworthyFlag, CONVERT( tinyint, NULL ) ), 
                 @BrokerEnabledFlag        = COALESCE( @BrokerEnabledFlag, CONVERT( tinyint, NULL ) ), 
                 @EncryptionFlag           = COALESCE( @EncryptionFlag, CONVERT( tinyint, NULL ) )
          FROM   master.dbo.sysdatabases d LEFT OUTER JOIN master.dbo.syslogins l 
                    ON d.sid = l.sid
          WHERE  d.name = @DatabaseName 
     END

     -- Condition All Flags
     SELECT @DatabaseReadOnlyFlag     = CASE WHEN @DatabaseReadOnlyFlag     != 1 OR @DatabaseReadOnlyFlag     IS NULL THEN 0 ELSE 1 END,
            @AutoCloseFlag            = CASE WHEN @AutoCloseFlag            != 1 OR @AutoCloseFlag            IS NULL THEN 0 ELSE 1 END,
            @AutoCreateStatsFlag      = CASE WHEN @AutoCreateStatsFlag      != 1 OR @AutoCreateStatsFlag      IS NULL THEN 0 ELSE 1 END,
            @AutoShrinkFlag           = CASE WHEN @AutoShrinkFlag           != 1 OR @AutoShrinkFlag           IS NULL THEN 0 ELSE 1 END,
            @AutoUpdateStatsFlag      = CASE WHEN @AutoUpdateStatsFlag      != 1 OR @AutoUpdateStatsFlag      IS NULL THEN 0 ELSE 1 END,
            @AutoUpdateStatsAsyncFlag = CASE WHEN @AutoUpdateStatsAsyncFlag != 1 OR @AutoUpdateStatsAsyncFlag IS NULL THEN 0 ELSE 1 END,
            @RecursiveTriggersFlag    = CASE WHEN @RecursiveTriggersFlag    != 1 OR @RecursiveTriggersFlag    IS NULL THEN 0 ELSE 1 END,
            @TrustworthyFlag          = CASE WHEN @TrustworthyFlag          != 1 OR @TrustworthyFlag          IS NULL THEN 0 ELSE 1 END,
            @BrokerEnabledFlag        = CASE WHEN @BrokerEnabledFlag        != 1 OR @BrokerEnabledFlag        IS NULL THEN 0 ELSE 1 END,
            @EncryptionFlag           = CASE WHEN @EncryptionFlag           != 1 OR @EncryptionFlag           IS NULL THEN 0 ELSE 1 END,
            @DatabaseDeletedFlag      = CASE WHEN @DatabaseDeletedFlag      != 1 OR @DatabaseDeletedFlag      IS NULL THEN 0 ELSE 1 END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncDatabase
                     WHERE  SrvrInstncId = @SrvrInstncId 
                     AND    DatabaseName = @DatabaseName )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncDatabase 
               ( SrvrInstncId,
                 PackageExecutionId,
                 DatabaseName,
                 EnabledFlag,
                 LastModDt )
          SELECT @SrvrInstncId,
                 @PackageExecutionId,
                 @DatabaseName,
                 1, -- EnabledFlag
                 CURRENT_TIMESTAMP

          SELECT @DBIdForSrv = SCOPE_IDENTITY()          

          IF ( @SrvrInstncTypeId = 1 ) -- MSSQL
          BEGIN
               INSERT dbo.SrvrInstncDatabaseMSSQL
                    ( SrvrInstncDatabaseId,
                      PackageExecutionId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      DatabaseId,
                      DatabaseOwnerName,
                      DateCreated,
                      DatabaseReadOnlyFlag,
                      CompatibilityLevel,
                      Collation,
                      DBStatus,
                      RecoveryModel,
                      AccessLevel,
                      AutoCloseFlag,
                      AutoCreateStatsFlag,
                      AutoShrinkFlag,
                      AutoUpdateStatsFlag,
                      AutoUpdateStatsAsyncFlag,
                      RecursiveTriggersFlag,
                      TrustworthyFlag,
                      BrokerEnabledFlag,
                      EncryptionFlag )
               SELECT @DBIdForSrv,
                      @PackageExecutionId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @DatabaseId,
                      @DatabaseOwnerName,
                      @DateCreated,
                      @DatabaseReadOnlyFlag,
                      @CompatibilityLevel,
                      @Collation,
                      @DBStatus,
                      @RecoveryModel,
                      @AccessLevel,
                      @AutoCloseFlag,
                      @AutoCreateStatsFlag,
                      @AutoShrinkFlag,
                      @AutoUpdateStatsFlag,
                      @AutoUpdateStatsAsyncFlag,
                      @RecursiveTriggersFlag,
                      @TrustworthyFlag,
                      @BrokerEnabledFlag,
                      @EncryptionFlag
          END -- MSSQL New Insert

          IF ( @SrvrInstncTypeId = 2 ) -- Oracle
          BEGIN
               RAISERROR( 'Oracle Is not currently implemented', 16, 1 )
          END

          IF ( @SrvrInstncTypeId = 3 ) -- Sybase
          BEGIN
               RAISERROR( 'Sybase Is not currently implemented', 16, 1 )
          END
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the Database Id
          SELECT @DBIdForSrv = SrvrInstncDatabaseId
          FROM   dbo.SrvrInstncDatabase
          WHERE  SrvrInstncId = @SrvrInstncId
          AND    DatabaseName = @DatabaseName

          -- Type Specific Work
          IF ( @SrvrInstncTypeId = 1 ) -- MSSQL
          BEGIN
               -- Get the startdt for the current record, if we are here one should
               -- be available, we perform a little trick here as well, taking 
               -- advantage or the ORDER BY  and making sure we have the maximum
               -- StartDt
               SELECT @StartDt = StartDt
               FROM   dbo.SrvrInstncDatabaseMSSQL
               WHERE  SrvrInstncDatabaseId = @DBIdForSrv
               AND    CurrentRecordFlag    = 1
               ORDER BY StartDt

               -- Reset current record flag to zero and set the end date to now minus
               -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
               -- not handle a difference less than 3ms.  Therefore it ends right before
               -- the new record starts with no overlap.
               UPDATE dbo.SrvrInstncDatabaseMSSQL 
               SET    EndDt             = DATEADD( ms, -3, @NOW ),
                      CurrentRecordFlag = 0
               WHERE  SrvrInstncDatabaseId = @DBIdForSrv
               AND    CurrentRecordFlag    = 1

               IF ( @DatabaseDeletedFlag = 0 )
               BEGIN -- Do regular checked insert
                    UPDATE dbo.SrvrInstncDatabase
                    SET    EnabledFlag = 1,
                           LastModDt   = CURRENT_TIMESTAMP
                    WHERE  SrvrInstncDatabaseId = @DBIdForSrv
                    AND    EnabledFlag = 0

                    INSERT dbo.SrvrInstncDatabaseMSSQL 
                         ( SrvrInstncDatabaseId,
                           PackageExecutionId,
                           StartDt,
                           EndDt,
                           CurrentRecordFlag,
                           DatabaseDeletedFlag,
                           DatabaseId,
                           DatabaseOwnerName,
                           DateCreated,
                           DatabaseReadOnlyFlag,
                           CompatibilityLevel,
                           Collation,
                           DBStatus,
                           RecoveryModel,
                           AccessLevel,
                           AutoCloseFlag,
                           AutoCreateStatsFlag,
                           AutoShrinkFlag,
                           AutoUpdateStatsFlag,
                           AutoUpdateStatsAsyncFlag,
                           RecursiveTriggersFlag,
                           TrustworthyFlag,
                           BrokerEnabledFlag,
                           EncryptionFlag )
                    SELECT @DBIdForSrv,
                           @PackageExecutionId,
                           @NOW, -- StartDt
                           '12/31/9999', -- EndDt
                           1, -- CurrentRecordFlag
                           DatabaseDeletedFlag = 0,
                           CASE WHEN DatabaseId         IS NOT NULL AND @DatabaseId         IS NULL THEN DatabaseId         ELSE @DatabaseId         END,
                           CASE WHEN DatabaseOwnerName  IS NOT NULL AND @DatabaseOwnerName  IS NULL THEN DatabaseOwnerName  ELSE @DatabaseOwnerName  END,
                           CASE WHEN DateCreated        IS NOT NULL AND @DateCreated        IS NULL THEN DateCreated        ELSE @DateCreated        END,
                           @DatabaseReadOnlyFlag,
                           CASE WHEN CompatibilityLevel IS NOT NULL AND @CompatibilityLevel IS NULL THEN CompatibilityLevel ELSE @CompatibilityLevel END,
                           CASE WHEN Collation          IS NOT NULL AND @Collation          IS NULL THEN Collation          ELSE @Collation          END,
                           CASE WHEN DBStatus           IS NOT NULL AND @DBStatus           IS NULL THEN DBStatus           ELSE @DBStatus           END,
                           CASE WHEN RecoveryModel      IS NOT NULL AND @RecoveryModel      IS NULL THEN RecoveryModel      ELSE @RecoveryModel      END,
                           CASE WHEN AccessLevel        IS NOT NULL AND @AccessLevel        IS NULL THEN AccessLevel        ELSE @AccessLevel        END,
                           @AutoCloseFlag,
                           @AutoCreateStatsFlag,
                           @AutoShrinkFlag,
                           @AutoUpdateStatsFlag,
                           @AutoUpdateStatsAsyncFlag,
                           @RecursiveTriggersFlag,
                           @TrustworthyFlag,
                           @BrokerEnabledFlag,
                           @EncryptionFlag
                    FROM   dbo.SrvrInstncDatabaseMSSQL
                    WHERE  SrvrInstncDatabaseId = @DBIdForSrv
                    AND    StartDt              = @StartDt
                    -- Decide if there will be an insert
                    AND  ( DatabaseDeletedFlag = 1
                           -- 1 = 0 -- Placeholder, always false, don't want to insert on accident
                        OR ( @DatabaseId IS NOT NULL               AND DatabaseId IS NULL )
                        OR ( @DatabaseOwnerName IS NOT NULL        AND DatabaseOwnerName IS NULL )
                        --OR ( @DateCreated IS NOT NULL              AND DateCreated IS NULL ) -- We aren't evaluating DateCreated
                        OR ( @DatabaseReadOnlyFlag IS NOT NULL     AND DatabaseReadOnlyFlag IS NULL )
                        OR ( @CompatibilityLevel IS NOT NULL       AND CompatibilityLevel IS NULL )
                        OR ( @Collation IS NOT NULL                AND Collation IS NULL )
                        OR ( @DBStatus IS NOT NULL                 AND DBStatus IS NULL )
                        OR ( @RecoveryModel IS NOT NULL            AND RecoveryModel IS NULL )
                        OR ( @AccessLevel IS NOT NULL              AND AccessLevel IS NULL )
                        OR ( @AutoCloseFlag IS NOT NULL            AND AutoCloseFlag IS NULL )
                        OR ( @AutoCreateStatsFlag IS NOT NULL      AND AutoCreateStatsFlag IS NULL )
                        OR ( @AutoShrinkFlag IS NOT NULL           AND AutoShrinkFlag IS NULL )
                        OR ( @AutoUpdateStatsFlag IS NOT NULL      AND AutoUpdateStatsFlag IS NULL )
                        OR ( @AutoUpdateStatsAsyncFlag IS NOT NULL AND AutoUpdateStatsAsyncFlag IS NULL )
                        OR ( @RecursiveTriggersFlag IS NOT NULL    AND RecursiveTriggersFlag IS NULL )
                        OR ( @TrustworthyFlag IS NOT NULL          AND TrustworthyFlag IS NULL )
                        OR ( @BrokerEnabledFlag IS NOT NULL        AND BrokerEnabledFlag IS NULL )
                        OR ( @EncryptionFlag IS NOT NULL           AND EncryptionFlag IS NULL )
                        OR ( @DatabaseId               != DatabaseId )
                        OR ( @DatabaseOwnerName        != DatabaseOwnerName )
                        --OR ( @DateCreated              != DateCreated ) -- We aren't evaluating DateCreated
                        OR ( @DatabaseReadOnlyFlag     != DatabaseReadOnlyFlag )
                        OR ( @CompatibilityLevel       != CompatibilityLevel )
                        OR ( @Collation                != Collation )
                        OR ( @DBStatus                 != DBStatus )
                        OR ( @RecoveryModel            != RecoveryModel )
                        OR ( @AccessLevel              != AccessLevel )
                        OR ( @AutoCloseFlag            != AutoCloseFlag )
                        OR ( @AutoCreateStatsFlag      != AutoCreateStatsFlag )
                        OR ( @AutoShrinkFlag           != AutoShrinkFlag )
                        OR ( @AutoUpdateStatsFlag      != AutoUpdateStatsFlag )
                        OR ( @AutoUpdateStatsAsyncFlag != AutoUpdateStatsAsyncFlag )
                        OR ( @RecursiveTriggersFlag    != RecursiveTriggersFlag )
                        OR ( @TrustworthyFlag          != TrustworthyFlag )
                        OR ( @BrokerEnabledFlag        != BrokerEnabledFlag )
                        OR ( @EncryptionFlag           != EncryptionFlag )
                        -- -- Taking this section out for now, basically if the 
                        -- -- record has data but the sproc call contains mostly 
                        -- -- nulls we don't want to wipe out data that we already 
                        -- -- have, so we won't accept this condition.
                        --OR ( @DatabaseId IS NULL                   AND DatabaseId IS NOT NULL )
                        --OR ( @DatabaseOwnerName IS NULL            AND DatabaseOwnerName IS NOT NULL )
                        ----OR ( @DateCreated IS NULL                  AND DateCreated IS NOT NULL ) -- We aren't evaluating DateCreated
                        --OR ( @DatabaseReadOnlyFlag IS NULL         AND DatabaseReadOnlyFlag IS NOT NULL )
                        --OR ( @CompatibilityLevel IS NULL           AND CompatibilityLevel IS NOT NULL )
                        --OR ( @Collation IS NULL                    AND Collation IS NOT NULL )
                        --OR ( @DBStatus IS NULL                     AND DBStatus IS NOT NULL )
                        --OR ( @RecoveryModel IS NULL                AND RecoveryModel IS NOT NULL )
                        --OR ( @AccessLevel IS NULL                  AND AccessLevel IS NOT NULL )
                        --OR ( @AutoCloseFlag IS NULL                AND AutoCloseFlag IS NOT NULL )
                        --OR ( @AutoCreateStatsFlag IS NULL          AND AutoCreateStatsFlag IS NOT NULL )
                        --OR ( @AutoShrinkFlag IS NULL               AND AutoShrinkFlag IS NOT NULL )
                        --OR ( @AutoUpdateStatsFlag IS NULL          AND AutoUpdateStatsFlag IS NOT NULL )
                        --OR ( @AutoUpdateStatsAsyncFlag IS NULL     AND AutoUpdateStatsAsyncFlag IS NOT NULL )
                        --OR ( @RecursiveTriggersFlag IS NULL        AND RecursiveTriggersFlag IS NOT NULL )
                        --OR ( @TrustworthyFlag IS NULL              AND TrustworthyFlag IS NOT NULL )
                        --OR ( @BrokerEnabledFlag IS NULL            AND BrokerEnabledFlag IS NOT NULL )
                        --OR ( @EncryptionFlag IS NULL               AND EncryptionFlag IS NOT NULL )
                         ) -- End of And-Or section

                    SELECT @RC = @@ROWCOUNT 
               END -- End of regular checked insert
               ELSE
               BEGIN -- Do database deleted insert
                    UPDATE dbo.SrvrInstncDatabase
                    SET    EnabledFlag = 0,
                           LastModDt   = CURRENT_TIMESTAMP
                    WHERE  SrvrInstncDatabaseId = @DBIdForSrv

                    INSERT dbo.SrvrInstncDatabaseMSSQL
                         ( SrvrInstncDatabaseId,
                           PackageExecutionId,
                           StartDt,
                           EndDt,
                           CurrentRecordFlag,
                           DatabaseDeletedFlag,
                           DatabaseId,
                           DatabaseOwnerName,
                           DateCreated,
                           DatabaseReadOnlyFlag,
                           CompatibilityLevel,
                           Collation,
                           DBStatus,
                           RecoveryModel,
                           AccessLevel,
                           AutoCloseFlag,
                           AutoCreateStatsFlag,
                           AutoShrinkFlag,
                           AutoUpdateStatsFlag,
                           AutoUpdateStatsAsyncFlag,
                           RecursiveTriggersFlag,
                           TrustworthyFlag,
                           BrokerEnabledFlag,
                           EncryptionFlag )
                    SELECT SrvrInstncDatabaseId,
                           @PackageExecutionId,
                           @NOW, -- StartDt
                           '12/31/9999', -- EndDt
                           1, -- CurrentRecordFlag
                           DatabaseDeletedFlag = 1,
                           DatabaseId,
                           DatabaseOwnerName,
                           DateCreated,
                           DatabaseReadOnlyFlag,
                           CompatibilityLevel,
                           Collation,
                           DBStatus,
                           RecoveryModel,
                           AccessLevel,
                           AutoCloseFlag,
                           AutoCreateStatsFlag,
                           AutoShrinkFlag,
                           AutoUpdateStatsFlag,
                           AutoUpdateStatsAsyncFlag,
                           RecursiveTriggersFlag,
                           TrustworthyFlag,
                           BrokerEnabledFlag,
                           EncryptionFlag
                    FROM   dbo.SrvrInstncDatabaseMSSQL
                    WHERE  SrvrInstncDatabaseId = @DBIdForSrv
                    AND    StartDt              = @StartDt

                    SELECT @RC = @@ROWCOUNT 
               END
          END -- End of Type 1 Existing Insert

          IF ( @SrvrInstncTypeId = 2 ) -- Oracle
          BEGIN
               RAISERROR( 'Oracle Is not currently implemented', 16, 1 )
          END

          IF ( @SrvrInstncTypeId = 3 ) -- Sybase
          BEGIN
               RAISERROR( 'Sybase Is not currently implemented', 16, 1 )
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance database record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncDatabase;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncDatabaseFileMSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncDatabaseFileMSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncDatabaseFileMSSQL
     @SrvrInstncDatabaseId          int,
     @PackageExecutionId            bigint,
     @DatabaseFileId                int              = NULL,
     @DatabaseFileGUID              uniqueidentifier = NULL,
     @FileIsLogFileFlag             tinyint          = NULL,
     @FileSizeInMB                  int              = NULL,
     @MaxFileSizeInMB               int              = NULL,
     @FileGrowthInMB                int              = NULL,
     @FileGrowthInPct               tinyint          = NULL,
     @FileGroupName                 varchar(128)     = NULL,
     @LogicalFileName               varchar(128)     = NULL,
     @PhysicalFileNameWithPath      varchar(255)     = NULL,
     @FileDeletedFlag               tinyint          = 0,
     @SrvrInstncDatabaseFileMSSQLId int              = NULL
AS
/*
 *
 * SaveSrvrInstncDatabaseFileMSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/09/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @MaxPEI  bigint,
             @RC      int,
             @NOW     datetime,
             @StartDt datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 

     -- Condition Flag
     SELECT @FileIsLogFileFlag = CASE WHEN @FileIsLogFileFlag != 1 OR @FileIsLogFileFlag IS NULL THEN 0 ELSE 1 END

     IF ( @FileDeletedFlag != 1 )
     BEGIN
          SELECT @SrvrInstncDatabaseFileMSSQLId = dbo.GetDatabaseFileMSSQLIdForServerDatabase
                                                        ( @SrvrInstncDatabaseId, 
                                                          @DatabaseFileId, 
                                                          @DatabaseFileGUID, 
                                                          @FileIsLogFileFlag, 
                                                          @LogicalFileName, 
                                                          @PhysicalFileNameWithPath )
     END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncDatabaseFileMSSQL
                     WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
                     AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncDatabaseFileMSSQL
               ( SrvrInstncDatabaseFileMSSQLId,
                 SrvrInstncDatabaseId,
                 PackageExecutionId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 DatabaseFileId,
                 DatabaseFileGUID,
                 FileIsLogFileFlag,
                 FileSizeInMB,
                 MaxFileSizeInMB,
                 FileGrowthInMB,
                 FileGrowthInPct,
                 FileGroupName,
                 LogicalFileName,
                 PhysicalFileNameWithPath )
          SELECT @SrvrInstncDatabaseFileMSSQLId,
                 @SrvrInstncDatabaseId,
                 @PackageExecutionId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @DatabaseFileId,
                 @DatabaseFileGUID,
                 @FileIsLogFileFlag,
                 @FileSizeInMB,
                 @MaxFileSizeInMB,
                 @FileGrowthInMB,
                 @FileGrowthInPct,
                 @FileGroupName,
                 @LogicalFileName,
                 @PhysicalFileNameWithPath
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncDatabaseFileMSSQL
          WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
          AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId
          AND    CurrentRecordFlag             = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncDatabaseFileMSSQL
          SET    EndDt             = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag = 0
          WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
          AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId
          AND    CurrentRecordFlag             = 1

          IF ( @FileDeletedFlag = 0 )
          BEGIN -- Do regular checked insert
               INSERT dbo.SrvrInstncDatabaseFileMSSQL
                    ( SrvrInstncDatabaseFileMSSQLId,
                      SrvrInstncDatabaseId,
                      PackageExecutionId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      FileDeletedFlag,
                      DatabaseFileId,
                      DatabaseFileGUID,
                      FileSizeInMB,
                      MaxFileSizeInMB,
                      FileIsLogFileFlag,
                      FileGrowthInMB,
                      FileGrowthInPct,
                      FileGroupName,
                      LogicalFileName,
                      PhysicalFileNameWithPath )
               SELECT @SrvrInstncDatabaseFileMSSQLId,
                      @SrvrInstncDatabaseId,
                      @PackageExecutionId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      FileDeletedFlag = 0,
                      CASE WHEN DatabaseFileId           IS NOT NULL AND @DatabaseFileId           IS NULL THEN DatabaseFileId           ELSE @DatabaseFileId           END,
                      CASE WHEN DatabaseFileGUID         IS NOT NULL AND @DatabaseFileGUID         IS NULL THEN DatabaseFileGUID         ELSE @DatabaseFileGUID         END,
                      CASE WHEN FileSizeInMB             IS NOT NULL AND @FileSizeInMB             IS NULL THEN FileSizeInMB             ELSE @FileSizeInMB             END,
                      CASE WHEN MaxFileSizeInMB          IS NOT NULL AND @MaxFileSizeInMB          IS NULL THEN MaxFileSizeInMB          ELSE @MaxFileSizeInMB          END,
                      @FileIsLogFileFlag,
                      @FileGrowthInMB,
                      @FileGrowthInPct,
                      CASE WHEN FileGroupName            IS NOT NULL AND @FileGroupName            IS NULL THEN FileGroupName            ELSE @FileGroupName            END,
                      CASE WHEN LogicalFileName          IS NOT NULL AND @LogicalFileName          IS NULL THEN LogicalFileName          ELSE @LogicalFileName          END, 
                      CASE WHEN PhysicalFileNameWithPath IS NOT NULL AND @PhysicalFileNameWithPath IS NULL THEN PhysicalFileNameWithPath ELSE @PhysicalFileNameWithPath END
               FROM   dbo.SrvrInstncDatabaseFileMSSQL
               WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
               AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId
               --AND    PackageExecutionId            = @MaxPEI
               AND    StartDt                       = @StartDt
               -- Decide if there will be an insert
               AND  ( FileDeletedFlag = 1
                      -- 1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR ( @DatabaseFileId IS NOT NULL           AND DatabaseFileId IS NULL )
                   OR ( @DatabaseFileGUID IS NOT NULL         AND DatabaseFileGUID IS NULL )
                   OR ( @FileSizeInMB IS NOT NULL             AND FileSizeInMB IS NULL ) 
                   OR ( @MaxFileSizeInMB IS NOT NULL          AND MaxFileSizeInMB IS NULL )
                   OR ( @FileGroupName IS NOT NULL            AND FileGroupName IS NULL ) 
                   OR ( @LogicalFileName IS NOT NULL          AND LogicalFileName IS NULL )
                   OR ( @PhysicalFileNameWithPath IS NOT NULL AND PhysicalFileNameWithPath IS NULL )
                   -- These two are kind of a special case, they can actually 
                   -- flip from one to the other so we want to be sure they can.
                   OR ( @FileGrowthInMB IS NOT NULL           AND FileGrowthInMB IS NULL )
                   OR ( @FileGrowthInMB IS NULL               AND FileGrowthInMB IS NOT NULL )
                   OR ( @FileGrowthInPct IS NOT NULL          AND FileGrowthInPct IS NULL )
                   OR ( @FileGrowthInPct IS NULL              AND FileGrowthInPct IS NOT NULL )
                   OR ( @DatabaseFileId                       != DatabaseFileId )
                   OR ( @DatabaseFileGUID                     != DatabaseFileGUID )
                   OR ( @FileSizeInMB                         != FileSizeInMB )
                   OR ( @MaxFileSizeInMB                      != MaxFileSizeInMB )
                   OR ( @FileGrowthInMB                       != FileGrowthInMB )
                   OR ( @FileGrowthInPct                      != FileGrowthInPct )
                   OR ( @FileGroupName                        != FileGroupName )
                   OR ( @LogicalFileName                      != LogicalFileName )
                   OR ( @PhysicalFileNameWithPath             != PhysicalFileNameWithPath )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               IF EXISTS ( SELECT 1 
                           FROM   dbo.SrvrInstncDatabaseFileMSSQL
                           WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
                           AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId
                           AND    StartDt                       = @StartDt
                           AND    FileDeletedFlag               = 0 )
               BEGIN -- Not already deleted.
                    INSERT dbo.SrvrInstncDatabaseFileMSSQL
                         ( SrvrInstncDatabaseFileMSSQLId,
                           SrvrInstncDatabaseId,
                           PackageExecutionId,
                           StartDt,
                           EndDt,
                           CurrentRecordFlag,
                           FileDeletedFlag,
                           DatabaseFileId,
                           DatabaseFileGUID,
                           FileIsLogFileFlag,
                           FileSizeInMB,
                           MaxFileSizeInMB,
                           FileGrowthInMB,
                           FileGrowthInPct,
                           FileGroupName,
                           LogicalFileName,
                           PhysicalFileNameWithPath )
                    SELECT SrvrInstncDatabaseFileMSSQLId,
                           SrvrInstncDatabaseId,
                           @PackageExecutionId,
                           @NOW, -- StartDt
                           '12/31/9999', -- EndDt
                           1, -- CurrentRecordFlag
                           FileDeletedFlag = 1,
                           DatabaseFileId,
                           DatabaseFileGUID,
                           FileIsLogFileFlag,
                           FileSizeInMB,
                           MaxFileSizeInMB,
                           FileGrowthInMB,
                           FileGrowthInPct,
                           FileGroupName,
                           LogicalFileName,
                           PhysicalFileNameWithPath
                    FROM   dbo.SrvrInstncDatabaseFileMSSQL
                    WHERE  SrvrInstncDatabaseId          = @SrvrInstncDatabaseId
                    AND    SrvrInstncDatabaseFileMSSQLId = @SrvrInstncDatabaseFileMSSQLId
                    --AND    PackageExecutionId            = @PEI
                    AND    StartDt                       = @StartDt

                    SELECT @RC = @@ROWCOUNT 
               END
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance database file for MSSSQL record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncDatabaseFileMSSQL;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncDatabaseSize' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncDatabaseSize
GO

CREATE PROCEDURE dbo.SaveSrvrInstncDatabaseSize
     @SrvrInstncDatabaseId int,
     @PackageExecutionId   bigint,
     @CaptureDt            datetime,
     @TotalDataSpaceMB     int,
     @TotalDataFiles       int,
     @TotalLogSpaceMB      int,
     @TotalLogFiles        int
AS
/*
 *
 * SaveSrvrInstncDatabaseSize
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 10/20/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @RC         int,
             @NOW        datetime,
             @TODAY      datetime,
             @MaxDt      datetime

     -- Get current date/time
     SELECT @NOW = @CaptureDt
     SELECT @TODAY = DATEADD( dd, DATEDIFF( dd, 0, @NOW ), 0 )

     -- Condition values
     SELECT @TotalDataSpaceMB = CASE WHEN @TotalDataSpaceMB < 1
                                     THEN 1
                                     ELSE @TotalDataSpaceMB
                                END,
            @TotalLogSpaceMB  = CASE WHEN @TotalLogSpaceMB < 1
                                     THEN 1
                                     ELSE @TotalLogSpaceMB
                                END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncDatabaseSize 
                     WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId
                     AND    CollectionDateOnly   = @TODAY )
     BEGIN -- We do not have this record, so we will do an insert
          INSERT dbo.SrvrInstncDatabaseSize
               ( SrvrInstncDatabaseId,
                 PackageExecutionId,
                 CaptureDt,
                 CurrentRecordForDtFlag,
                 TotalDataSpaceMB,
                 TotalDataFiles,
                 TotalLogSpaceMB,
                 TotalLogFiles )
          SELECT @SrvrInstncDatabaseId,
                 @PackageExecutionId,
                 @NOW, -- CollectionDt
                 1, -- CurrentRecordForDtFlag
                 @TotalDataSpaceMB,
                 @TotalDataFiles,
                 @TotalLogSpaceMB,
                 @TotalLogFiles
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get @MaxDt
          SELECT @MaxDt = CaptureDt
          FROM   dbo.SrvrInstncDatabaseSize 
          WHERE  SrvrInstncDatabaseId   = @SrvrInstncDatabaseId 
          AND    CollectionDateOnly     = @TODAY 
          AND    CurrentRecordForDtFlag = 1
          
          -- Reset current record for date flag to zero
          UPDATE dbo.SrvrInstncDatabaseSize 
          SET    CurrentRecordForDtFlag = 0
          WHERE  SrvrInstncDatabaseId   = @SrvrInstncDatabaseId 
          AND    CollectionDateOnly     = @TODAY 
          AND    CurrentRecordForDtFlag = 1

          -- Do regular checked insert
          INSERT dbo.SrvrInstncDatabaseSize
               ( SrvrInstncDatabaseId,
                 PackageExecutionId,
                 CaptureDt,
                 CurrentRecordForDtFlag,
                 TotalDataSpaceMB,
                 TotalDataFiles,
                 TotalLogSpaceMB,
                 TotalLogFiles )
          SELECT @SrvrInstncDatabaseId,
                 @PackageExecutionId,
                 @NOW, -- CaptureDt
                 1, -- CurrentRecordForDtFlag
                 @TotalDataSpaceMB,
                 @TotalDataFiles,
                 @TotalLogSpaceMB,
                 @TotalLogFiles
          FROM   dbo.SrvrInstncDatabaseSize
          WHERE  SrvrInstncDatabaseId = @SrvrInstncDatabaseId 
          AND    CaptureDt            = @MaxDt 
          -- Decide if there will be an insert
          AND  ( 1 = 0 -- Placeholder, always false, don't want to insert on accident
              OR ( @TotalDataSpaceMB != TotalDataSpaceMB )
              OR ( @TotalDataFiles   != TotalDataFiles )
              OR ( @TotalLogSpaceMB  != TotalLogSpaceMB )
              OR ( @TotalLogFiles    != TotalLogFiles )
               ) -- End of And-Or section

          SELECT @RC = @@ROWCOUNT 

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance database size record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncDatabaseSize;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncEAV' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncEAV
GO

CREATE PROCEDURE dbo.SaveSrvrInstncEAV
     @SrvrInstncId             int,
     @ParameterId              int,
     @ParameterMultiId         int = 0,
     @ParameterValue           varchar(8000),
     @InsertOnlyFlag           tinyint = 0
AS
/*
 *
 * SaveSrvrInstncEAV
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/09/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @NOW      datetime,
             @DefValue varchar(8000)

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 

     -- Get default value
     SELECT @DefValue = ParameterDefaultValue
     FROM   dbo.Parameter
     WHERE  ParameterId = @ParameterId

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncEAV
                     WHERE  SrvrInstncId     = @SrvrInstncId
                     AND    ParameterId      = @ParameterId
                     AND    ParameterMultiId = @ParameterMultiId )
     BEGIN -- We do not have this record, so we will do an insert
          INSERT dbo.SrvrInstncEAV
               ( SrvrInstncId,
                 ParameterId,
                 ParameterMultiId,
                 ParameterValue,
                 LastModDt )
          SELECT @SrvrInstncId,
                 @ParameterId,
                 @ParameterMultiId,
                 @ParameterValue,
                 @NOW
     END -- End New insert
     ELSE
     BEGIN -- We have the record so we do an insert if there is a difference. If we are allowed
          IF ( @InsertOnlyFlag = 0 )
          BEGIN
               UPDATE dbo.SrvrInstncEAV
               SET    ParameterValue   = @ParameterValue,
                      LastModDt        = @NOW
               WHERE  SrvrInstncId     = @SrvrInstncId
               AND    ParameterId      = @ParameterId
               AND    ParameterMultiId = @ParameterMultiId
               AND  ( ParameterValue != @ParameterValue
                   OR ParameterValue IS     NULL AND @ParameterValue IS NOT NULL
                   OR ParameterValue IS NOT NULL AND @ParameterValue IS     NULL )
               -- LastModDt is not compared as it is only metadata and not data proper.
          END
     END
END
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncMachine' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncMachine
GO

CREATE PROCEDURE dbo.SaveSrvrInstncMachine
     @SrvrInstncId       int,
     @MachineId          int,
     @PackageExecutionId bigint
AS
/*
 *
 * SaveSrvrInstncMachine
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 09/29/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     -- Check to see if the combination exists, if not insert it.
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncMachine
                     WHERE  SrvrInstncId = @SrvrInstncId
                     AND    MachineId    = @MachineId )
     BEGIN -- Do the insert.
          INSERT dbo.SrvrInstncMachine 
               ( SrvrInstncId,
                 MachineId,
                 PackageExecutionId )
          SELECT @SrvrInstncId,
                 @MachineId,
                 @PackageExecutionId
     END
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance record tieing a machine record to a server instance record, this represents that the server instance can/has run on that underlying machine.  This sproc is called by SaveSrvrMachineSrvrInstncMachine.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncMachine;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncSchedJobMSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncSchedJobMSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncSchedJobMSSQL
     @SrvrInstncId             int,
     @PackageExecutionId       bigint,
     @JobIdentifier            varchar(50),
     @JobName                  varchar(128),
     @JobEnabledFlag           tinyint,
     @JobDescription           varchar(1024),
     @OwnerName                varchar(128),
     @CategoryId               int,
     @CategoryName             varchar(128),
     @StartStepId              int,
     @NotifyLevelEventlogDesc  varchar(30),
     @NotifyLevelEmailDesc     varchar(30),
     @NotifyLevelNetsendDesc   varchar(30),
     @NotifyLevelPageDesc      varchar(30),
     @NotifyEmailOperator      varchar(128),
     @NotifyNetsendOperator    varchar(128),
     @NotifyPageOperator       varchar(128),
     @CrDt                     datetime,
     @ModDt                    datetime,
     @VersionNumber            int,
     @JobDeletedFlag           tinyint       = 0
AS
/*
 *
 * SaveSrvrInstncSchedJobMSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 05/30/2009, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @JobIdForSrv int,
             @StartDt     datetime, 
             --@PEI         bigint,
             @RC          int,
             @NOW         datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Condition Flags
     SELECT @JobEnabledFlag = CASE WHEN @JobEnabledFlag != 1 OR @JobEnabledFlag IS NULL THEN 0 ELSE 1 END,
            @JobDeletedFlag = CASE WHEN @JobDeletedFlag != 1 OR @JobDeletedFlag IS NULL THEN 0 ELSE 1 END

     -- Condition Input
     SELECT @JobDescription = ISNULL( @JobDescription, '' )
     
     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncSchedJobMSSQL
                     WHERE  SrvrInstncId  = @SrvrInstncId 
                     AND    JobIdentifier = @JobIdentifier )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          -- Get the job Id 
          SELECT @JobIdForSrv = ISNULL(MAX(SrvrInstncSchedJobId),0) + 1
          FROM   dbo.SrvrInstncSchedJobMSSQL
          WHERE  SrvrInstncId  = @SrvrInstncId 

          INSERT dbo.SrvrInstncSchedJobMSSQL
               ( SrvrInstncId,
                 SrvrInstncSchedJobId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 PackageExecutionId,
                 JobDeletedFlag,
                 JobIdentifier,
                 JobName,
                 JobEnabledFlag,
                 JobDescription,
                 OwnerName,
                 CategoryId,
                 CategoryName,
                 StartStepId,
                 NotifyLevelEventlogDesc,
                 NotifyLevelEmailDesc,
                 NotifyLevelNetsendDesc,
                 NotifyLevelPageDesc,
                 NotifyEmailOperator,
                 NotifyNetsendOperator,
                 NotifyPageOperator,
                 CrDt,
                 ModDt,
                 VersionNumber )
          SELECT @SrvrInstncId,
                 @JobIdForSrv,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @PackageExecutionId,
                 0, -- JobDeletedFlag
                 @JobIdentifier,
                 @JobName,
                 @JobEnabledFlag,
                 @JobDescription,
                 @OwnerName,
                 @CategoryId,
                 @CategoryName,
                 @StartStepId,
                 @NotifyLevelEventlogDesc,
                 @NotifyLevelEmailDesc,
                 @NotifyLevelNetsendDesc,
                 @NotifyLevelPageDesc,
                 @NotifyEmailOperator,
                 @NotifyNetsendOperator,
                 @NotifyPageOperator,
                 @CrDt,
                 @ModDt,
                 @VersionNumber 
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the job Id 
          SELECT @JobIdForSrv = SrvrInstncSchedJobId 
          FROM   dbo.SrvrInstncSchedJobMSSQL 
          WHERE  SrvrInstncId  = @SrvrInstncId 
          AND    JobIdentifier = @JobIdentifier

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncSchedJobMSSQL
          WHERE  SrvrInstncId         = @SrvrInstncId
          AND    SrvrInstncSchedJobId = @JobIdForSrv
          AND    CurrentRecordFlag    = 1
          ORDER BY StartDt

          ---- Get PEI for current record, we should have one if we are here..
          --SELECT @PEI = PackageExecutionId
          --FROM   dbo.SrvrInstncSchedJobMSSQL
          --WHERE  SrvrInstncId         = @SrvrInstncId 
          --AND    SrvrInstncSchedJobId = @JobIdForSrv
          --AND    CurrentRecordFlag    = 1

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncSchedJobMSSQL  
          SET    EndDt             = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag = 0
          WHERE  SrvrInstncId         = @SrvrInstncId 
          AND    SrvrInstncSchedJobId = @JobIdForSrv
          AND    CurrentRecordFlag    = 1

          IF ( @JobDeletedFlag = 0 )
          BEGIN -- Do regular insert
               INSERT dbo.SrvrInstncSchedJobMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      JobDeletedFlag,
                      JobIdentifier,
                      JobName,
                      JobEnabledFlag,
                      JobDescription,
                      OwnerName,
                      CategoryId,
                      CategoryName,
                      StartStepId,
                      NotifyLevelEventlogDesc,
                      NotifyLevelEmailDesc,
                      NotifyLevelNetsendDesc,
                      NotifyLevelPageDesc,
                      NotifyEmailOperator,
                      NotifyNetsendOperator,
                      NotifyPageOperator,
                      CrDt,
                      ModDt,
                      VersionNumber )
               SELECT @SrvrInstncId,
                      @JobIdForSrv,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      0, -- JobDeletedFlag
                      @JobIdentifier,
                      @JobName,
                      @JobEnabledFlag,
                      @JobDescription,
                      @OwnerName,
                      @CategoryId,
                      @CategoryName,
                      @StartStepId,
                      @NotifyLevelEventlogDesc,
                      @NotifyLevelEmailDesc,
                      @NotifyLevelNetsendDesc,
                      @NotifyLevelPageDesc,
                      @NotifyEmailOperator,
                      @NotifyNetsendOperator,
                      @NotifyPageOperator,
                      @CrDt,
                      @ModDt,
                      @VersionNumber 
               FROM   dbo.SrvrInstncSchedJobMSSQL
               WHERE  SrvrInstncId         = @SrvrInstncId 
               AND    SrvrInstncSchedJobId = @JobIdForSrv
               AND    StartDt              = @StartDt
               -- Decide if there will be an insert
               AND  ( JobDeletedFlag = 1
                      --1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR ( @JobName                 != JobName )
                   OR ( @JobEnabledFlag          != JobEnabledFlag )
                   OR ( @JobDescription          != JobDescription )
                   OR ( @OwnerName               != OwnerName )
                   OR ( @CategoryId              != CategoryId )
                   OR ( @CategoryName            != CategoryName )
                   OR ( @StartStepId             != StartStepId )
                   OR ( @NotifyLevelEventlogDesc != NotifyLevelEventlogDesc )
                   OR ( @NotifyLevelEmailDesc    != NotifyLevelEmailDesc )
                   OR ( @NotifyLevelNetsendDesc  != NotifyLevelNetsendDesc )
                   OR ( @NotifyLevelPageDesc     != NotifyLevelPageDesc )
                   OR ( @NotifyEmailOperator     != NotifyEmailOperator )
                   OR ( @NotifyNetsendOperator   != NotifyNetsendOperator )
                   OR ( @NotifyPageOperator      != NotifyPageOperator )
                   OR ( @CrDt                    != CrDt )
                   OR ( @ModDt                   != ModDt )
                   OR ( @VersionNumber           != VersionNumber )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               INSERT dbo.SrvrInstncSchedJobMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      JobDeletedFlag,
                      JobIdentifier,
                      JobName,
                      JobEnabledFlag,
                      JobDescription,
                      OwnerName,
                      CategoryId,
                      CategoryName,
                      StartStepId,
                      NotifyLevelEventlogDesc,
                      NotifyLevelEmailDesc,
                      NotifyLevelNetsendDesc,
                      NotifyLevelPageDesc,
                      NotifyEmailOperator,
                      NotifyNetsendOperator,
                      NotifyPageOperator,
                      CrDt,
                      ModDt,
                      VersionNumber )
               SELECT SrvrInstncId,
                      SrvrInstncSchedJobId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      1, -- JobDeletedFlag
                      JobIdentifier,
                      JobName,
                      JobEnabledFlag,
                      JobDescription,
                      OwnerName,
                      CategoryId,
                      CategoryName,
                      StartStepId,
                      NotifyLevelEventlogDesc,
                      NotifyLevelEmailDesc,
                      NotifyLevelNetsendDesc,
                      NotifyLevelPageDesc,
                      NotifyEmailOperator,
                      NotifyNetsendOperator,
                      NotifyPageOperator,
                      CrDt,
                      ModDt,
                      VersionNumber 
               FROM   dbo.SrvrInstncSchedJobMSSQL 
               WHERE  SrvrInstncId         = @SrvrInstncId
               AND    SrvrInstncSchedJobId = @JobIdForSrv
               AND    StartDt              = @StartDt
               AND    JobDeletedFlag       = 0 -- Don't re-delete it..

               SELECT @RC = @@ROWCOUNT 
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance scheduled job MS SQL specific record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncSchedJobMSSQL;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncSchedJobScheduleMSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncSchedJobScheduleMSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncSchedJobScheduleMSSQL
     @SrvrInstncId             int,
     @PackageExecutionId       bigint,
     @SrvrInstncSchedJobId     int,
     @ScheduleIdentifier       uniqueidentifier,
     @ScheduleId               int,
     @ScheduleName             varchar(128),
     @ScheduleOriginServerName varchar(128),
     @ScheduleOwnerName        varchar(128),
     @ScheduleEnabledFlag      tinyint,
     @ScheduleCrDt             datetime,
     @ScheduleLastModDt        datetime,
     @ScheduleVersion          int,
     @CodedRawSchedule         varchar(120),
     @freq_type                int,
     @freq_interval            int,
     @freq_subday_type         int,
     @freq_subday_interval     int,
     @freq_relative_interval   int,
     @freq_recurrence_factor   int,
     @active_start_date        int,
     @active_end_date          int,
     @active_start_time        int,
     @active_end_time          int,
     @ScheduleDeletedFlag      tinyint       = 0
AS
/*
 *
 * SaveSrvrInstncSchedJobStepMSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/10/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @StartDt     datetime,
             @PEI         bigint,
             @RC          int,
             @NOW         datetime,
             @SchedDesc   varchar(255)

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Condition Flags and data
     SELECT @ScheduleDeletedFlag = CASE WHEN @ScheduleDeletedFlag != 1 OR @ScheduleDeletedFlag IS NULL THEN 0 ELSE 1 END
     SELECT @SchedDesc = ISNULL( dbo.GetMSSQLJobScheduleDescription( @freq_type, 
                                                                     @freq_interval, 
                                                                     @freq_subday_type, 
                                                                     @freq_subday_interval, 
                                                                     @freq_relative_interval, 
                                                                     @freq_recurrence_factor, 
                                                                     @active_start_date, 
                                                                     @active_end_date, 
                                                                     @active_start_time, 
                                                                     @active_end_time ), 
                                 'Unable to decode schedule' )

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncSchedJobScheduleMSSQL
                     WHERE  SrvrInstncId         = @SrvrInstncId 
                     AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
                     AND    ScheduleId           = @ScheduleId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncSchedJobScheduleMSSQL
               ( SrvrInstncId,
                 SrvrInstncSchedJobId,
                 ScheduleId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 PackageExecutionId,
                 ScheduleDeletedFlag,
                 ScheduleIdentifier,
                 ScheduleName,
                 ScheduleOriginServerName,
                 ScheduleOwnerName,
                 ScheduleEnabledFlag,
                 ScheduleDescription,
                 ScheduleCrDt,
                 ScheduleLastModDt,
                 ScheduleVersion,
                 CodedRawSchedule )
          SELECT @SrvrInstncId,
                 @SrvrInstncSchedJobId,
                 @ScheduleId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @PackageExecutionId,
                 0, -- ScheduleDeletedFlag
                 @ScheduleIdentifier,
                 @ScheduleName,
                 @ScheduleOriginServerName,
                 @ScheduleOwnerName,
                 @ScheduleEnabledFlag,
                 @SchedDesc,
                 @ScheduleCrDt,
                 @ScheduleLastModDt,
                 @ScheduleVersion,
                 @CodedRawSchedule
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncSchedJobStepMSSQL
          WHERE  SrvrInstncId         = @SrvrInstncId
          AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
          AND    StepId               = @ScheduleId
          AND    CurrentRecordFlag    = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncSchedJobStepMSSQL  
          SET    EndDt             = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag = 0
          WHERE  SrvrInstncId         = @SrvrInstncId 
          AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
          AND    StepId               = @ScheduleId
          AND    CurrentRecordFlag    = 1

          IF ( @ScheduleDeletedFlag = 0 )
          BEGIN -- Do regular insert
               INSERT dbo.SrvrInstncSchedJobScheduleMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      ScheduleId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      ScheduleDeletedFlag,
                      ScheduleIdentifier,
                      ScheduleName,
                      ScheduleOriginServerName,
                      ScheduleOwnerName,
                      ScheduleEnabledFlag,
                      ScheduleDescription,
                      ScheduleCrDt,
                      ScheduleLastModDt,
                      ScheduleVersion,
                      CodedRawSchedule )
               SELECT @SrvrInstncId,
                      @SrvrInstncSchedJobId,
                      @ScheduleId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      0, -- ScheduleDeletedFlag
                      @ScheduleIdentifier,
                      @ScheduleName,
                      @ScheduleOriginServerName,
                      @ScheduleOwnerName,
                      @ScheduleEnabledFlag,
                      @SchedDesc,
                      @ScheduleCrDt,
                      @ScheduleLastModDt,
                      @ScheduleVersion,
                      @CodedRawSchedule
               FROM   dbo.SrvrInstncSchedJobScheduleMSSQL
               WHERE  SrvrInstncId         = @SrvrInstncId 
               AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
               AND    ScheduleId           = @ScheduleId
               AND    StartDt              = @StartDt
               -- Decide if there will be an insert
               AND  ( ScheduleDeletedFlag = 1
                      --1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR ( @ScheduleName             != ScheduleName )
                   OR ( @ScheduleOriginServerName != ScheduleOriginServerName )
                   OR ( @ScheduleOwnerName        != ScheduleOwnerName )
                   OR ( @ScheduleEnabledFlag      != ScheduleEnabledFlag )
                   OR ( @SchedDesc                != ScheduleDescription )
                   OR ( @ScheduleCrDt             != ScheduleCrDt )
                   OR ( @CodedRawSchedule != CodedRawSchedule )
                   -- Handle nullable columns
                   OR ( @ScheduleIdentifier       != ScheduleIdentifier
                     OR ( @ScheduleIdentifier IS     NULL AND ScheduleIdentifier IS NOT NULL ) 
                     OR ( @ScheduleIdentifier IS NOT NULL AND ScheduleIdentifier IS     NULL ) )
                   OR ( @ScheduleLastModDt        != ScheduleLastModDt
                     OR ( @ScheduleLastModDt  IS     NULL AND ScheduleLastModDt  IS NOT NULL ) 
                     OR ( @ScheduleLastModDt  IS NOT NULL AND ScheduleLastModDt  IS     NULL ) )
                   OR ( @ScheduleVersion          != ScheduleVersion
                     OR ( @ScheduleVersion    IS     NULL AND ScheduleVersion    IS NOT NULL ) 
                     OR ( @ScheduleVersion    IS NOT NULL AND ScheduleVersion    IS     NULL ) )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               INSERT dbo.SrvrInstncSchedJobScheduleMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      ScheduleId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      ScheduleDeletedFlag,
                      ScheduleIdentifier,
                      ScheduleName,
                      ScheduleOriginServerName,
                      ScheduleOwnerName,
                      ScheduleEnabledFlag,
                      ScheduleDescription,
                      ScheduleCrDt,
                      ScheduleLastModDt,
                      ScheduleVersion,
                      CodedRawSchedule )
               SELECT SrvrInstncId,
                      SrvrInstncSchedJobId,
                      ScheduleId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      1, -- ScheduleDeletedFlag
                      ScheduleIdentifier,
                      ScheduleName,
                      ScheduleOriginServerName,
                      ScheduleOwnerName,
                      ScheduleEnabledFlag,
                      ScheduleDescription,
                      ScheduleCrDt,
                      ScheduleLastModDt,
                      ScheduleVersion,
                      CodedRawSchedule
               FROM   dbo.SrvrInstncSchedJobScheduleMSSQL 
               WHERE  SrvrInstncId         = @SrvrInstncId
               AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
               AND    ScheduleId           = @ScheduleId
               AND    StartDt              = @StartDt

               SELECT @RC = @@ROWCOUNT 
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance scheduled job step MS SQL specific record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncSchedJobScheduleMSSQL;
GO
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncSchedJobStepMSSQL' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncSchedJobStepMSSQL
GO

CREATE PROCEDURE dbo.SaveSrvrInstncSchedJobStepMSSQL
     @SrvrInstncId                   int,
     @PackageExecutionId             bigint,
     @SrvrInstncSchedJobId           int,
     @StepIdentifier                 uniqueidentifier,
     @StepId                         int,
     @StepName                       varchar(128),
     @SubSystem                      varchar(40),
     @Command                        nvarchar(MAX),
     @IncludeStepOutputInHistoryFlag tinyint,
     @LogToTableFlag                 tinyint,
     @LogToTableAppendOutputFlag     tinyint,
     @AppendOutputToOutputFileFlag   tinyint,
     @CmdExecSuccessCode             int,
     @OnSuccessAction                varchar(30),
     @OnFailAction                   varchar(30),
     @OnSuccessStepId                int,
     @OnFailStepId                   int,
     @ServerName                     varchar(128),
     @DatabaseName                   varchar(128),
     @DatabaseUserName               varchar(128),
     @RetryAttempts                  int,
     @RetryIntervalInMinutes         int,
     @OSRunPriority                  int,
     @OutputFileName                 varchar(200),
     @ProxyName                      varchar(128),
     @StepDeletedFlag                tinyint       = 0
AS
/*
 *
 * SaveSrvrInstncSchedJobStepMSSQL
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/10/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @StartDt     datetime,
             @PEI         bigint,
             @RC          int,
             @NOW         datetime

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 
     
     -- Condition Flags
     SELECT @StepDeletedFlag = CASE WHEN @StepDeletedFlag != 1 OR @StepDeletedFlag IS NULL THEN 0 ELSE 1 END

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncSchedJobStepMSSQL
                     WHERE  SrvrInstncId         = @SrvrInstncId 
                     AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
                     AND    StepId               = @StepId )
     BEGIN -- We do not have this record, so we will do an insert, we should
           -- Never have a delete here as well so we will not test for it.
          INSERT dbo.SrvrInstncSchedJobStepMSSQL
               ( SrvrInstncId,
                 SrvrInstncSchedJobId,
                 StepId,
                 StartDt,
                 EndDt,
                 CurrentRecordFlag,
                 PackageExecutionId,
                 StepDeletedFlag,
                 StepIdentifier,
                 StepName,
                 SubSystem,
                 Command,
                 IncludeStepOutputInHistoryFlag,
                 LogToTableFlag,
                 LogToTableAppendOutputFlag,
                 AppendOutputToOutputFileFlag,
                 CmdExecSuccessCode,
                 OnSuccessAction,
                 OnFailAction,
                 OnSuccessStepId,
                 OnFailStepId,
                 ServerName,
                 DatabaseName,
                 DatabaseUserName,
                 RetryAttempts,
                 RetryIntervalInMinutes,
                 OSRunPriority,
                 OutputFileName,
                 ProxyName )
          SELECT @SrvrInstncId,
                 @SrvrInstncSchedJobId,
                 @StepId,
                 @NOW, -- StartDt
                 '12/31/9999', -- EndDt
                 1, -- CurrentRecordFlag
                 @PackageExecutionId,
                 0, -- StepDeletedFlag
                 @StepIdentifier,
                 @StepName,
                 @SubSystem,
                 @Command,
                 @IncludeStepOutputInHistoryFlag,
                 @LogToTableFlag,
                 @LogToTableAppendOutputFlag,
                 @AppendOutputToOutputFileFlag,
                 @CmdExecSuccessCode,
                 @OnSuccessAction,
                 @OnFailAction,
                 @OnSuccessStepId,
                 @OnFailStepId,
                 @ServerName,
                 @DatabaseName,
                 @DatabaseUserName,
                 @RetryAttempts,
                 @RetryIntervalInMinutes,
                 @OSRunPriority,
                 @OutputFileName,
                 @ProxyName
     END -- End New insert
     ELSE
     BEGIN -- We have at least one copy of this record, so we may do an insert
          BEGIN TRANSACTION

          -- Get the startdt for the current record, if we are here one should
          -- be available, we perform a little trick here as well, taking 
          -- advantage or the ORDER BY  and making sure we have the maximum
          -- StartDt
          SELECT @StartDt = StartDt
          FROM   dbo.SrvrInstncSchedJobStepMSSQL
          WHERE  SrvrInstncId         = @SrvrInstncId
          AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
          AND    StepId               = @StepId
          AND    CurrentRecordFlag    = 1
          ORDER BY StartDt

          -- Reset current record flag to zero and set the end date to now minus
          -- 3 ms, 3ms was chosen due to the granularity of the datetype, it does
          -- not handle a difference less than 3ms.  Therefore it ends right before
          -- the new record starts with no overlap.
          UPDATE dbo.SrvrInstncSchedJobStepMSSQL  
          SET    EndDt             = DATEADD( ms, -3, @NOW ),
                 CurrentRecordFlag = 0
          WHERE  SrvrInstncId         = @SrvrInstncId 
          AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
          AND    StepId               = @StepId
          AND    CurrentRecordFlag    = 1

          IF ( @StepDeletedFlag = 0 )
          BEGIN -- Do regular insert
               INSERT dbo.SrvrInstncSchedJobStepMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      StepId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      StepDeletedFlag,
                      StepIdentifier,
                      StepName,
                      SubSystem,
                      Command,
                      IncludeStepOutputInHistoryFlag,
                      LogToTableFlag,
                      LogToTableAppendOutputFlag,
                      AppendOutputToOutputFileFlag,
                      CmdExecSuccessCode,
                      OnSuccessAction,
                      OnFailAction,
                      OnSuccessStepId,
                      OnFailStepId,
                      ServerName,
                      DatabaseName,
                      DatabaseUserName,
                      RetryAttempts,
                      RetryIntervalInMinutes,
                      OSRunPriority,
                      OutputFileName,
                      ProxyName )
               SELECT @SrvrInstncId,
                      @SrvrInstncSchedJobId,
                      @StepId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      0, -- StepDeletedFlag
                      @StepIdentifier,
                      @StepName,
                      @SubSystem,
                      @Command,
                      @IncludeStepOutputInHistoryFlag,
                      @LogToTableFlag,
                      @LogToTableAppendOutputFlag,
                      @AppendOutputToOutputFileFlag,
                      @CmdExecSuccessCode,
                      @OnSuccessAction,
                      @OnFailAction,
                      @OnSuccessStepId,
                      @OnFailStepId,
                      @ServerName,
                      @DatabaseName,
                      @DatabaseUserName,
                      @RetryAttempts,
                      @RetryIntervalInMinutes,
                      @OSRunPriority,
                      @OutputFileName,
                      @ProxyName
               FROM   dbo.SrvrInstncSchedJobStepMSSQL
               WHERE  SrvrInstncId         = @SrvrInstncId 
               AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
               AND    StepId               = @StepId
               AND    StartDt              = @StartDt
               -- Decide if there will be an insert
               AND  ( StepDeletedFlag = 1
                      --1 = 0 -- Placeholder, always false, don't want to insert on accident
                   OR ( @StepIdentifier                 != StepIdentifier )
                   OR ( @StepName                       != StepName )
                   OR ( @SubSystem                      != SubSystem )
                   OR ( @Command                        != Command )
                   OR ( @IncludeStepOutputInHistoryFlag != IncludeStepOutputInHistoryFlag )
                   OR ( @LogToTableFlag                 != LogToTableFlag )
                   OR ( @LogToTableAppendOutputFlag     != LogToTableAppendOutputFlag )
                   OR ( @AppendOutputToOutputFileFlag   != AppendOutputToOutputFileFlag )
                   OR ( @CmdExecSuccessCode             != CmdExecSuccessCode )
                   OR ( @OnSuccessAction                != OnSuccessAction )
                   OR ( @OnFailAction                   != OnFailAction )
                   OR ( @OnSuccessStepId                != OnSuccessStepId )
                   OR ( @OnFailStepId                   != OnFailStepId )
                   OR ( @RetryAttempts                  != RetryAttempts )
                   OR ( @RetryIntervalInMinutes         != RetryIntervalInMinutes )
                   OR ( @OSRunPriority                  != OSRunPriority )
                   -- Handle nullable columns
                   --OR ( @StepIdentifier   != StepIdentifier 
                   --  OR ( @StepIdentifier   IS     NULL AND StepIdentifier   IS NOT NULL )
                   --  OR ( @StepIdentifier   IS NOT NULL AND StepIdentifier   IS     NULL ) )
                   OR ( @ServerName       != ServerName 
                     OR ( @ServerName       IS     NULL AND ServerName       IS NOT NULL ) 
                     OR ( @ServerName       IS NOT NULL AND ServerName       IS     NULL ) )
                   OR ( @DatabaseName     != DatabaseName
                     OR ( @DatabaseName     IS     NULL AND DatabaseName     IS NOT NULL )
                     OR ( @DatabaseName     IS NOT NULL AND DatabaseName     IS     NULL ) )
                   OR ( @DatabaseUserName != DatabaseUserName
                     OR ( @DatabaseUserName IS     NULL AND DatabaseUserName IS NOT NULL )
                     OR ( @DatabaseUserName IS NOT NULL AND DatabaseUserName IS     NULL ) )
                   OR ( @OutputFileName   != OutputFileName
                     OR ( @OutputFileName   IS     NULL AND OutputFileName   IS NOT NULL )
                     OR ( @OutputFileName   IS NOT NULL AND OutputFileName   IS     NULL ) )
                   OR ( @ProxyName        != ProxyName
                     OR ( @ProxyName        IS     NULL AND ProxyName        IS NOT NULL )
                     OR ( @ProxyName        IS NOT NULL AND ProxyName        IS     NULL ) )
                    ) -- End of And-Or section

               SELECT @RC = @@ROWCOUNT 
          END -- End of regular checked insert
          ELSE
          BEGIN -- Do database deleted insert
               INSERT dbo.SrvrInstncSchedJobStepMSSQL
                    ( SrvrInstncId,
                      SrvrInstncSchedJobId,
                      StepId,
                      StartDt,
                      EndDt,
                      CurrentRecordFlag,
                      PackageExecutionId,
                      StepDeletedFlag,
                      StepIdentifier,
                      StepName,
                      SubSystem,
                      Command,
                      IncludeStepOutputInHistoryFlag,
                      LogToTableFlag,
                      LogToTableAppendOutputFlag,
                      AppendOutputToOutputFileFlag,
                      CmdExecSuccessCode,
                      OnSuccessAction,
                      OnFailAction,
                      OnSuccessStepId,
                      OnFailStepId,
                      ServerName,
                      DatabaseName,
                      DatabaseUserName,
                      RetryAttempts,
                      RetryIntervalInMinutes,
                      OSRunPriority,
                      OutputFileName,
                      ProxyName )
               SELECT SrvrInstncId,
                      SrvrInstncSchedJobId,
                      StepId,
                      @NOW, -- StartDt
                      '12/31/9999', -- EndDt
                      1, -- CurrentRecordFlag
                      @PackageExecutionId,
                      1, -- StepDeletedFlag
                      StepIdentifier,
                      StepName,
                      SubSystem,
                      Command,
                      IncludeStepOutputInHistoryFlag,
                      LogToTableFlag,
                      LogToTableAppendOutputFlag,
                      AppendOutputToOutputFileFlag,
                      CmdExecSuccessCode,
                      OnSuccessAction,
                      OnFailAction,
                      OnSuccessStepId,
                      OnFailStepId,
                      ServerName,
                      DatabaseName,
                      DatabaseUserName,
                      RetryAttempts,
                      RetryIntervalInMinutes,
                      OSRunPriority,
                      OutputFileName,
                      ProxyName
               FROM   dbo.SrvrInstncSchedJobStepMSSQL 
               WHERE  SrvrInstncId         = @SrvrInstncId
               AND    SrvrInstncSchedJobId = @SrvrInstncSchedJobId
               AND    StepId               = @StepId
               AND    StartDt              = @StartDt

               SELECT @RC = @@ROWCOUNT 
          END

          IF ( @RC = 1 )
          BEGIN -- We did do an insert so we commit it.
               COMMIT TRANSACTION
          END
          ELSE
          BEGIN -- We did not do any insert, this is not an error, but we will 
                -- do a rollback since we want to keep the last current record.
               ROLLBACK TRANSACTION
          END
     END -- End Existing Insert
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Save a server instance scheduled job step MS SQL specific record if anything has changed from the previous run, calls to this sproc will NOT always generate a new record.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = SaveSrvrInstncSchedJobStepMSSQL;
GO
IF  EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_dts_addlogentry]') AND type in (N'P', N'PC'))
BEGIN
     DROP PROCEDURE [dbo].[sp_dts_addlogentry]
END
GO

CREATE PROCEDURE [dbo].[sp_dts_addlogentry]
     @event       sysname,
     @computer    nvarchar(128),
     @operator    nvarchar(128),
     @source      nvarchar(1024),
     @sourceid    uniqueidentifier,
     @executionid uniqueidentifier,
     @starttime   datetime,
     @endtime     datetime,
     @datacode    int,
     @databytes   image,
     @message     nvarchar(2048)
AS
/*
 *
 * sp_dts_addlogentry
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/18/2011, 1.00.0000
 *
 */
BEGIN
     INSERT dbo.EventLog
          ( EventLogTypeId,
            LogByApp,
            LogByAppSubSystem,
            MiscVC1,
            MiscVC2,
            MiscVC3,
            TraceText,
            MiscGUID1,
            MiscGUID4,
            MiscDt1,
            MiscDt2,
            MiscInt1,
            MiscTinyint1,
            TraceImage,
            LogText )
     SELECT 1, -- Informational
            'Integration Services',
            'sp_dts_addlogentry',
            @event,
            @computer,
            @operator,
            @source,
            @sourceid,
            @executionid,
            @starttime,
            @endtime,
            @datacode,
            9, -- SSIS version, SQL 2005
            @databytes,
            @message
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a SSIS (SQL 2005) log entry into the EventLog table.  This sproc name is the standard name that the SSIS SQL Server logging is expecting, instead of writing the data to a MS specifically named table it is written into the EventLog table.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = sp_dts_addlogentry;
GO
IF  EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ssis_addlogentry]') AND type in (N'P', N'PC'))
BEGIN
     DROP PROCEDURE [dbo].[sp_ssis_addlogentry]
END
GO

CREATE PROCEDURE [dbo].[sp_ssis_addlogentry]
     @event       sysname,
     @computer    nvarchar(128),
     @operator    nvarchar(128),
     @source      nvarchar(1024),
     @sourceid    uniqueidentifier,
     @executionid uniqueidentifier,
     @starttime   datetime,
     @endtime     datetime,
     @datacode    int,
     @databytes   image,
     @message     nvarchar(2048)
AS
/*
 *
 * sp_ssis_addlogentry
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Calling
 * Application:  
 *
 * Note(s):      
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/18/2011, 1.00.0000
 *
 */
BEGIN
     INSERT dbo.EventLog
          ( EventLogTypeId,
            LogByApp,
            LogByAppSubSystem,
            MiscVC1,
            MiscVC2,
            MiscVC3,
            TraceText,
            MiscGUID1,
            MiscGUID4,
            MiscDt1,
            MiscDt2,
            MiscInt1,
            MiscTinyint1,
            TraceImage,
            LogText )
     SELECT 1, -- Informational
            'Integration Services',
            'sp_ssis_addlogentry',
            @event,
            @computer,
            @operator,
            @source,
            @sourceid,
            @executionid,
            @starttime,
            @endtime,
            @datacode,
            10, -- SSIS version, SQL 2008
            @databytes,
            @message
END
GO

EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Inserts a SSIS (SQL 2008) log entry into the EventLog table.  This sproc name is the standard name that the SSIS SQL Server logging is expecting, instead of writing the data to a MS specifically named table it is written into the EventLog table.', @level0type = N'Schema', @level0name = dbo, @level1type = N'PROCEDURE', @level1name = sp_ssis_addlogentry;
GO
IF  EXISTS (SELECT * FROM sys.fulltext_indexes fti WHERE fti.object_id = OBJECT_ID(N'[dbo].[MasterEventLog]'))
BEGIN
     ALTER FULLTEXT INDEX ON [dbo].[MasterEventLog] DISABLE
END
GO

IF  EXISTS (SELECT * FROM sys.fulltext_indexes fti WHERE fti.object_id = OBJECT_ID(N'[dbo].[MasterEventLog]'))
BEGIN
     DROP FULLTEXT INDEX ON [dbo].[MasterEventLog]
END
GO

IF  EXISTS (SELECT * FROM sysfulltextcatalogs ftc WHERE ftc.name = N'MasterEventLogFTCatalog') 
BEGIN
     DROP FULLTEXT CATALOG [MasterEventLogFTCatalog]
END
GO

CREATE FULLTEXT CATALOG [MasterEventLogFTCatalog]WITH ACCENT_SENSITIVITY = ON AUTHORIZATION [dbo]
GO

CREATE FULLTEXT INDEX ON [dbo].[MasterEventLog](
     [AppName]           LANGUAGE [English], 
     [DatabaseName]      LANGUAGE [English], 
     [DatabaseUserName]  LANGUAGE [English], 
     [HostName]          LANGUAGE [English], 
     [LogByApp]          LANGUAGE [English], 
     [LogByAppSubSystem] LANGUAGE [English], 
     [LogByDesc]         LANGUAGE [English], 
     [LoginName]         LANGUAGE [English], 
     [LogText]           LANGUAGE [English], 
     [MiscVC1]           LANGUAGE [English], 
     [MiscVC2]           LANGUAGE [English], 
     [MiscVC3]           LANGUAGE [English], 
     [MiscVC4]           LANGUAGE [English], 
     [TraceText]         LANGUAGE [English])
     KEY INDEX [IX_MasterEventLog_RecordGUID] 
          ON ([MasterEventLogFTCatalog], FILEGROUP [Data_FTIndex]) WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)
GO
IF  EXISTS (SELECT * FROM sysfulltextcatalogs ftc WHERE ftc.name = N'SrvrInstncSchedJobHistoryMSSQLFTCatalog')
BEGIN
     DROP FULLTEXT CATALOG [SrvrInstncSchedJobHistoryMSSQLFTCatalog]
END
GO

CREATE FULLTEXT CATALOG [SrvrInstncSchedJobHistoryMSSQLFTCatalog]WITH ACCENT_SENSITIVITY = ON AUTHORIZATION [dbo]
GO
-- -----------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- 
-- Initial Population
-- 
-- -----------------------------------------------------------------------------
-- -----------------------------------------------------------------------------

-- dbo.CfgCtrl
DELETE FROM dbo.CfgCtrl WHERE CfgCtrlKey IN ( 'MinMinutesBetweenVolSpcSamples' )
GO

INSERT dbo.CfgCtrl
     ( CfgCtrlKey, CfgCtrlValue, CfgCtrlDescription )
SELECT 'MinMinutesBetweenVolSpcSamples', '55', 'Minimum number of minutes between VolumeSpace samples'
GO

-- Populate dbo.EventLogType
TRUNCATE TABLE dbo.EventLog
GO
DELETE FROM dbo.EventLogType 
GO

INSERT dbo.EventLogType 
     ( EventLogTypeId, EventLogTypeCd, EventLogTypeDesc ) 
SELECT 0, 'UNK', 'Unknown'
UNION ALL
SELECT 1, 'INFO', 'Informational'
UNION ALL
SELECT 2, 'WARN', 'Warning'
UNION ALL
SELECT 3, 'FAIL', 'Failure'
GO

-- dbo.Parameter
DELETE FROM dbo.Parameter
GO

INSERT dbo.Parameter
     ( ParameterId, ParameterCd, ParameterName, ParameterDefaultValue, ParamAllowMutliFlag, ParamMaxMultiCnt )
SELECT 100, 'MaxJobHistoryId', 'The maximum job history id for this server instance id', '0', 0, 0
UNION ALL
SELECT 101, 'MaxEventLogId', 'The maximum event log id for this database in a server instance.', '0', 1, -1
UNION ALL
SELECT 200, 'ELHDatabaseId', 'The database id to retrieve the Event Log History from', '1', 1, -1
UNION ALL
SELECT 201, 'ExecLogDatabaseId', 'The database id to retrieve the ExecutionLog, ExecutionLog2, or ExecutionLog3 from', '1', 1, -1 )
GO

-- dbo.SrvrInstncGrp
DELETE FROM [dbo].[SrvrInstncGrp]
GO

INSERT dbo.SrvrInstncGrp
     ( SrvrInstncGrpId, SrvrInstncGrpPriority, SrvrInstncGrpName)
SELECT 1, 0, 'Default Group'
GO

-- dbo.SrvrInstncType
DELETE FROM dbo.SrvrInstncType 
GO

INSERT dbo.SrvrInstncType 
     ( SrvrInstncTypeId, SrvrInstncTypeCd, SrvrInstncTypeName, OLEDBProviderName) 
SELECT 1, 'MSSQL', 'Microsoft SQL Server', 'SQLNCLI10'
UNION ALL
SELECT 2, 'ORACLE', 'Oracle', 'Do Not Know'
UNION ALL
SELECT 3, 'SYBASE', 'Sybase', 'Do Not Know'
UNION ALL
SELECT 4, 'DB2C', 'DB2-C', 'Do Not Know'
GO

-- dbo.Seq
TRUNCATE TABLE dbo.Seq
GO

INSERT dbo.Seq ( SeqName, SeqNumber ) VALUES ( 'PackageExecutionId', 0 )
GO

